List of usage examples for javax.servlet.http HttpServletResponse setBufferSize
public void setBufferSize(int size);
From source file:net.dorokhov.pony.web.server.common.StreamingViewRenderer.java
@Override protected void renderMergedOutputModel(Map objectMap, HttpServletRequest request, HttpServletResponse response) throws Exception { InputStream dataStream = (InputStream) objectMap.get(DownloadConstants.INPUT_STREAM); if (dataStream == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return;//from ww w. jav a2s. co m } long length = (Long) objectMap.get(DownloadConstants.CONTENT_LENGTH); String fileName = (String) objectMap.get(DownloadConstants.FILENAME); Date lastModifiedObj = (Date) objectMap.get(DownloadConstants.LAST_MODIFIED); if (StringUtils.isEmpty(fileName) || lastModifiedObj == null) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } long lastModified = lastModifiedObj.getTime(); String contentType = (String) objectMap.get(DownloadConstants.CONTENT_TYPE); // Validate request headers for caching --------------------------------------------------- // If-None-Match header should contain "*" or ETag. If so, then return 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && matches(ifNoneMatch, fileName)) { response.setHeader("ETag", fileName); // Required in 304. response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } // If-Modified-Since header should be greater than LastModified. If so, then return 304. // This header is ignored if any If-None-Match header is specified. long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) { response.setHeader("ETag", fileName); // Required in 304. response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } // Validate request headers for resume ---------------------------------------------------- // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !matches(ifMatch, fileName)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // If-Unmodified-Since header should be greater than LastModified. If not, then return 412. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Validate and process range ------------------------------------------------------------- // Prepare some variables. The full Range represents the complete file. Range full = new Range(0, length - 1, length); List<Range> ranges = new ArrayList<>(); // Validate and process Range and If-Range headers. String range = request.getHeader("Range"); if (range != null) { // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416. if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(fileName)) { try { long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid. if (ifRangeTime != -1) { ranges.add(full); } } catch (IllegalArgumentException ignore) { ranges.add(full); } } // If any valid If-Range header, then process each part of byte range. if (ranges.isEmpty()) { for (String part : range.substring(6).split(",")) { // Assuming a file with length of 100, the following examples returns bytes at: // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100). long start = sublong(part, 0, part.indexOf("-")); long end = sublong(part, part.indexOf("-") + 1, part.length()); if (start == -1) { start = length - end; end = length - 1; } else if (end == -1 || end > length - 1) { end = length - 1; } // Check if Range is syntactically valid. If not, then return 416. if (start > end) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // Add range. ranges.add(new Range(start, end, length)); } } } // Prepare and initialize response -------------------------------------------------------- // Get content type by file name and set content disposition. String disposition = "inline"; // If content type is unknown, then set the default value. // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp // To add new content types, add new mime-mapping entry in web.xml. if (contentType == null) { contentType = "application/octet-stream"; } else if (!contentType.startsWith("image")) { // Else, expect for images, determine content disposition. If content type is supported by // the browser, then set to inline, else attachment which will pop a 'save as' dialogue. String accept = request.getHeader("Accept"); disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment"; } // Initialize response. response.reset(); response.setBufferSize(DEFAULT_BUFFER_SIZE); response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", fileName); response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME); // Send requested file (part(s)) to client ------------------------------------------------ // Prepare streams. InputStream input = null; OutputStream output = null; try { // Open streams. input = new BufferedInputStream(dataStream); output = response.getOutputStream(); if (ranges.isEmpty() || ranges.get(0) == full) { // Return full file. response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + full.start + "-" + full.end + "/" + full.total); response.setHeader("Content-Length", String.valueOf(full.length)); copy(input, output, length, full.start, full.length); } else if (ranges.size() == 1) { // Return single part of file. Range r = ranges.get(0); response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); response.setHeader("Content-Length", String.valueOf(r.length)); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. // Copy single part range. copy(input, output, length, r.start, r.length); } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. // Cast back to ServletOutputStream to get the easy println methods. ServletOutputStream sos = (ServletOutputStream) output; // Copy multi part range. for (Range r : ranges) { // Add multipart boundary and header fields for every range. sos.println(); sos.println("--" + MULTIPART_BOUNDARY); sos.println("Content-Type: " + contentType); sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total); // Copy single part range of multi part range. copy(input, output, length, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + MULTIPART_BOUNDARY + "--"); } } finally { // Gently close streams. close(output); close(input); close(dataStream); } }
From source file:com.swingtech.apps.filemgmt.controller.StreamingViewRenderer.java
@Override protected void renderMergedOutputModel(Map objectMap, HttpServletRequest request, HttpServletResponse response) throws Exception { InputStream dataStream = (InputStream) objectMap.get(DownloadConstants.INPUT_STREAM); if (dataStream == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return;/*from ww w . ja v a 2 s. c o m*/ } long length = (Long) objectMap.get(DownloadConstants.CONTENT_LENGTH); String fileName = (String) objectMap.get(DownloadConstants.FILENAME); Date lastModifiedObj = (Date) objectMap.get(DownloadConstants.LAST_MODIFIED); if (StringUtils.isEmpty(fileName) || lastModifiedObj == null) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } long lastModified = lastModifiedObj.getTime(); String contentType = (String) objectMap.get(DownloadConstants.CONTENT_TYPE); // Validate request headers for caching // --------------------------------------------------- // If-None-Match header should contain "*" or ETag. If so, then return // 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && HttpUtils.matches(ifNoneMatch, fileName)) { response.setHeader("ETag", fileName); // Required in 304. response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } // If-Modified-Since header should be greater than LastModified. If so, // then return 304. // This header is ignored if any If-None-Match header is specified. long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) { response.setHeader("ETag", fileName); // Required in 304. response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } // Validate request headers for resume // ---------------------------------------------------- // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !HttpUtils.matches(ifMatch, fileName)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // If-Unmodified-Since header should be greater than LastModified. If // not, then return 412. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Validate and process range // ------------------------------------------------------------- // Prepare some variables. The full Range represents the complete file. Range full = new Range(0, length - 1, length); List<Range> ranges = new ArrayList<Range>(); // Validate and process Range and If-Range headers. String range = request.getHeader("Range"); if (range != null) { // Range header should match format "bytes=n-n,n-n,n-n...". If not, // then return 416. if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { response.setHeader("Content-Range", "bytes */" + length); // Required // in // 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(fileName)) { try { long ifRangeTime = request.getDateHeader("If-Range"); // Throws // IAE // if // invalid. if (ifRangeTime != -1) { ranges.add(full); } } catch (IllegalArgumentException ignore) { ranges.add(full); } } // If any valid If-Range header, then process each part of byte // range. if (ranges.isEmpty()) { for (String part : range.substring(6).split(",")) { // Assuming a file with length of 100, the following // examples returns bytes at: // 50-80 (50 to 80), 40- (40 to length=100), -20 // (length-20=80 to length=100). long start = StringUtils.sublong(part, 0, part.indexOf("-")); long end = StringUtils.sublong(part, part.indexOf("-") + 1, part.length()); if (start == -1) { start = length - end; end = length - 1; } else if (end == -1 || end > length - 1) { end = length - 1; } // Check if Range is syntactically valid. If not, then // return 416. if (start > end) { response.setHeader("Content-Range", "bytes */" + length); // Required // in // 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // Add range. ranges.add(new Range(start, end, length)); } } } // Prepare and initialize response // -------------------------------------------------------- // Get content type by file name and set content disposition. String disposition = "inline"; // If content type is unknown, then set the default value. // For all content types, see: // http://www.w3schools.com/media/media_mimeref.asp // To add new content types, add new mime-mapping entry in web.xml. if (contentType == null) { contentType = "application/octet-stream"; } else if (!contentType.startsWith("image")) { // Else, expect for images, determine content disposition. If // content type is supported by // the browser, then set to inline, else attachment which will pop a // 'save as' dialogue. String accept = request.getHeader("Accept"); disposition = accept != null && HttpUtils.accepts(accept, contentType) ? "inline" : "attachment"; } // Initialize response. response.reset(); response.setBufferSize(DEFAULT_BUFFER_SIZE); response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", fileName); response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME); // Send requested file (part(s)) to client // ------------------------------------------------ // Prepare streams. InputStream input = null; OutputStream output = null; try { // Open streams. input = new BufferedInputStream(dataStream); output = response.getOutputStream(); if (ranges.isEmpty() || ranges.get(0) == full) { // Return full file. Range r = full; response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); response.setHeader("Content-Length", String.valueOf(r.length)); copy(input, output, length, r.start, r.length); } else if (ranges.size() == 1) { // Return single part of file. Range r = ranges.get(0); response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); response.setHeader("Content-Length", String.valueOf(r.length)); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. // Copy single part range. copy(input, output, length, r.start, r.length); } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. // Cast back to ServletOutputStream to get the easy println // methods. ServletOutputStream sos = (ServletOutputStream) output; // Copy multi part range. for (Range r : ranges) { // Add multipart boundary and header fields for every range. sos.println(); sos.println("--" + MULTIPART_BOUNDARY); sos.println("Content-Type: " + contentType); sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total); // Copy single part range of multi part range. copy(input, output, length, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + MULTIPART_BOUNDARY + "--"); } } finally { // Gently close streams. close(output); close(input); close(dataStream); } }
From source file:com.harrywu.springweb.common.StreamingViewRenderer.java
@Override public void renderMergedOutputModel(Map<String, Object> objectMap, HttpServletRequest request, HttpServletResponse response) throws Exception { InputStream dataStream = (InputStream) objectMap.get(INPUT_STREAM); if (dataStream == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return;//from w w w. ja v a2 s .c om } long length = (Long) objectMap.get(CONTENT_LENGTH); String fileName = (String) objectMap.get(FILENAME); Date lastModifiedObj = (Date) objectMap.get(LAST_MODIFIED); if (StringUtils.isEmpty(fileName) || lastModifiedObj == null) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); return; } long lastModified = lastModifiedObj.getTime(); String contentType = (String) objectMap.get(CONTENT_TYPE); // Validate request headers for caching // --------------------------------------------------- // If-None-Match header should contain "*" or ETag. If so, then return // 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && matches(ifNoneMatch, fileName)) { response.setHeader("ETag", fileName); // Required in 304. response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } // If-Modified-Since header should be greater than LastModified. If so, // then return 304. // This header is ignored if any If-None-Match header is specified. long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) { response.setHeader("ETag", fileName); // Required in 304. response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } // Validate request headers for resume // ---------------------------------------------------- // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !matches(ifMatch, fileName)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // If-Unmodified-Since header should be greater than LastModified. If // not, then return 412. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Validate and process range // ------------------------------------------------------------- // Prepare some variables. The full Range represents the complete file. Range full = new Range(0, length - 1, length); List<Range> ranges = new ArrayList<Range>(); // Validate and process Range and If-Range headers. String range = request.getHeader("Range"); if (range != null) { // Range header should match format "bytes=n-n,n-n,n-n...". If not, // then return 416. if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { response.setHeader("Content-Range", "bytes */" + length); // Required // in // 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(fileName)) { try { long ifRangeTime = request.getDateHeader("If-Range"); // Throws // IAE // if // invalid. if (ifRangeTime != -1) { ranges.add(full); } } catch (IllegalArgumentException ignore) { ranges.add(full); } } // If any valid If-Range header, then process each part of byte // range. if (ranges.isEmpty()) { for (String part : range.substring(6).split(",")) { // Assuming a file with length of 100, the following // examples returns bytes at: // 50-80 (50 to 80), 40- (40 to length=100), -20 // (length-20=80 to length=100). long start = sublong(part, 0, part.indexOf("-")); long end = sublong(part, part.indexOf("-") + 1, part.length()); if (start == -1) { start = length - end; end = length - 1; } else if (end == -1 || end > length - 1) { end = length - 1; } // Check if Range is syntactically valid. If not, then // return 416. if (start > end) { response.setHeader("Content-Range", "bytes */" + length); // Required // in // 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // Add range. ranges.add(new Range(start, end, length)); } } } // Prepare and initialize response // -------------------------------------------------------- // Get content type by file name and set content disposition. String disposition = "inline"; // If content type is unknown, then set the default value. // For all content types, see: // http://www.w3schools.com/media/media_mimeref.asp // To add new content types, add new mime-mapping entry in web.xml. if (contentType == null) { contentType = "application/octet-stream"; } else if (!contentType.startsWith("image")) { // Else, expect for images, determine content disposition. If // content type is supported by // the browser, then set to inline, else attachment which will pop a // 'save as' dialogue. String accept = request.getHeader("Accept"); disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment"; } // Initialize response. response.reset(); response.setBufferSize(DEFAULT_BUFFER_SIZE); response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", fileName); response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME); // Send requested file (part(s)) to client // ------------------------------------------------ // Prepare streams. InputStream input = null; OutputStream output = null; try { // Open streams. input = new BufferedInputStream(dataStream); output = response.getOutputStream(); if (ranges.isEmpty() || ranges.get(0) == full) { // Return full file. Range r = full; response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); response.setHeader("Content-Length", String.valueOf(r.length)); copy(input, output, length, r.start, r.length); } else if (ranges.size() == 1) { // Return single part of file. Range r = ranges.get(0); response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); response.setHeader("Content-Length", String.valueOf(r.length)); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. // Copy single part range. copy(input, output, length, r.start, r.length); } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. // Cast back to ServletOutputStream to get the easy println // methods. ServletOutputStream sos = (ServletOutputStream) output; // Copy multi part range. for (Range r : ranges) { // Add multipart boundary and header fields for every range. sos.println(); sos.println("--" + MULTIPART_BOUNDARY); sos.println("Content-Type: " + contentType); sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total); // Copy single part range of multi part range. copy(input, output, length, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + MULTIPART_BOUNDARY + "--"); } } finally { // Gently close streams. close(output); close(input); close(dataStream); } }
From source file:org.sakaiproject.dav.DavServlet.java
/** * Handle requests for content, resources ONLY * //from w w w . j a v a2s.c o m * @param id * The local resource id. * @param res * The http servlet response object. * @return any error message, or null if all went well. */ private String doContent(String id, HttpServletRequest req, HttpServletResponse res) throws IOException { if (prohibited(id)) { res.sendError(HttpServletResponse.SC_FORBIDDEN); return rb.getString("permission_to_view"); } // resource or collection? check the properties (also finds bad id and checks permissions) boolean isCollection = false; try { ResourceProperties props = null; try { props = contentHostingService.getProperties(adjustId(id)); } catch (IdUnusedException x) { if (!id.endsWith(Entity.SEPARATOR)) { String tempid = id + Entity.SEPARATOR; props = contentHostingService.getProperties(adjustId(tempid)); id = tempid; } else { res.sendError(HttpServletResponse.SC_NOT_FOUND); return rb.getString("resource_not_exists"); } } isCollection = props.getBooleanProperty(ResourceProperties.PROP_IS_COLLECTION); } catch (PermissionException e) { res.sendError(HttpServletResponse.SC_FORBIDDEN); return rb.getString("permission_to_view"); } catch (IdUnusedException e) { res.sendError(HttpServletResponse.SC_NOT_FOUND); return rb.getString("resource_not_exists"); } catch (EntityPropertyNotDefinedException e) { res.sendError(HttpServletResponse.SC_NOT_FOUND); return rb.getString("resource_not_exists"); } catch (EntityPropertyTypeException e) { res.sendError(HttpServletResponse.SC_NOT_FOUND); return rb.getString("resource_not_exists"); } // for resources if (!isCollection) { if (M_log.isDebugEnabled()) M_log.debug("SAKAIAccess doContent is resource " + id); InputStream contentStream = null; OutputStream out = null; try { ContentResource resource = contentHostingService.getResource(adjustId(id)); long len = resource.getContentLength(); String contentType = resource.getContentType(); // for URL content type, encode a redirect to the body URL if (contentType.equalsIgnoreCase(ResourceProperties.TYPE_URL)) { res.sendRedirect(new String(resource.getContent())); } else { // Similar to handleAccessResource() in BaseContentService.java contentStream = resource.streamContent(); if (contentStream == null || len == 0) { return rb.getString("empty_resource"); } // set the buffer of the response to match what we are reading from the request if (len < STREAM_BUFFER_SIZE) { res.setBufferSize((int) len); } else { res.setBufferSize(STREAM_BUFFER_SIZE); } if (!processHead(req, res)) return rb.getString("error_setting_header_values"); out = res.getOutputStream(); // chunk content stream to response byte[] chunk = new byte[STREAM_BUFFER_SIZE]; int lenRead; while ((lenRead = contentStream.read(chunk)) != -1) { out.write(chunk, 0, lenRead); } } } catch (Throwable e) { // M_log.warn(this + ".doContent(): exception: id: " + id + " : " + e.toString()); return e.toString(); } finally { if (contentStream != null) { try { contentStream.close(); } catch (IOException e) { // ignore } } if (out != null) { try { out.close(); } catch (Throwable ignore) { // ignore } } } } // for collections else { doDirectory(id, req, res); } // no errors return null; }
From source file:org.sakaiproject.message.impl.BaseMessageService.java
/** * {@inheritDoc}//from w w w .j a va2 s.co m */ public HttpAccess getHttpAccess() { return new HttpAccess() { public void handleAccess(HttpServletRequest req, HttpServletResponse res, Reference ref, Collection copyrightAcceptedRefs) throws EntityPermissionException, EntityNotDefinedException { try { // We need to write to a temporary stream for better speed, plus // so we can get a byte count. Internet Explorer has problems // if we don't make the setContentLength() call. ByteArrayOutputStream outByteStream = new ByteArrayOutputStream(); OutputStreamWriter sw = new OutputStreamWriter(outByteStream); String skin = m_serverConfigurationService.getString("skin.default"); String skinRepo = m_serverConfigurationService.getString("skin.repo"); Message message = getMessage(ref); String title = ref.getDescription(); MessageHeader messageHead = message.getHeader(); String date = messageHead.getDate().toStringLocalFullZ(); //Integer message_order=messageHead.getMessage_order(); String from = messageHead.getFrom().getDisplayName(); StringBuilder groups = new StringBuilder(); Collection gr = messageHead.getGroups(); for (Iterator i = gr.iterator(); i.hasNext();) { groups.append("<li>" + i.next() + "</li>"); } String body = message.getBody(); sw.write( "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" + "<html xmlns=\"http://www.w3.org/1999/xhtml\" lang=\"en\" xml:lang=\"en\">\n" + "<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />\n" + "<link href=\""); sw.write(skinRepo); sw.write("/tool_base.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />\n" + "<link href=\""); sw.write(skinRepo); sw.write("/"); sw.write(skin); sw.write("/tool.css\" type=\"text/css\" rel=\"stylesheet\" media=\"all\" />\n" + "<meta http-equiv=\"Content-Style-Type\" content=\"text/css\" />\n" + "<title>"); sw.write(title); sw.write("</title></head><body><div class=\"portletBody\">\n" + "<h2>"); sw.write(title); sw.write("</h2><ul><li>Date "); sw.write(date); sw.write("</li>"); sw.write("<li>From "); sw.write(from); sw.write("</li>"); sw.write(groups.toString()); sw.write("<ul><p>"); sw.write(body); sw.write("</p></div></body></html> "); sw.flush(); res.setContentType("text/html"); res.setContentLength(outByteStream.size()); if (outByteStream.size() > 0) { // Increase the buffer size for more speed. res.setBufferSize(outByteStream.size()); } OutputStream out = null; try { out = res.getOutputStream(); if (outByteStream.size() > 0) { outByteStream.writeTo(out); } out.flush(); out.close(); } catch (Throwable ignore) { } finally { if (out != null) { try { out.close(); } catch (Throwable ignore) { } } } } catch (PermissionException e) { throw new EntityPermissionException(e.getUser(), e.getLocalizedMessage(), e.getResource()); } catch (IdUnusedException e) { throw new EntityNotDefinedException(e.getId()); } catch (Throwable t) { throw new RuntimeException("Faied to find message ", t); } } }; }
From source file:eionet.gdem.web.FileDownloadServlet.java
/** * Process the actual request.//from w ww. ja va2s. c om * * @param request * The request to be processed. * @param response * The response to be created. * @param content * Whether the request body should be written (GET) or not (HEAD). * @throws IOException * If something fails at I/O level. * @throws ServletException If an error occurs. */ private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException, ServletException { String urlPath = URLDecoder .decode(StringUtils.substringAfter(request.getRequestURI(), request.getContextPath()), "UTF-8"); String filePath = Properties.appRootFolder + urlPath; String securityMessage = checkPermissions(request, urlPath); if (securityMessage != null) { handleNotAuthorised(securityMessage, request, response); return; } // Get the file object from the file store File file = new File(filePath); // If file was not found, send 404. if (file == null || !file.exists() || !file.isFile()) { handleFileNotFound("Could not find file by the following URI: " + request.getRequestURI(), request, response); return; } // Prepare some variables. The ETag is an unique identifier of the file. String fileName = file.getName(); long length = file.length(); long lastModified = file.lastModified(); String eTag = fileName + "_" + length + "_" + lastModified; // Validate request headers for caching --------------------------------------------------- // If-None-Match header should contain "*" or ETag. If so, then return 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) { response.setHeader("ETag", eTag); // Required in 304. response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } // If-Modified-Since header should be greater than LastModified. If so, then return 304. // This header is ignored if any If-None-Match header is specified. long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) { response.setHeader("ETag", eTag); // Required in 304. response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } // Validate request headers for resume ---------------------------------------------------- // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !matches(ifMatch, eTag)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // If-Unmodified-Since header should be greater than LastModified. If not, then return 412. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Validate and process range ------------------------------------------------------------- // Prepare some variables. The full Range represents the complete file. Range full = new Range(0, length - 1, length); List<Range> ranges = new ArrayList<Range>(); // Validate and process Range and If-Range headers. String range = request.getHeader("Range"); if (range != null) { // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416. if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // If-Range header should either match ETag or be greater then LastModified. If not, // then return full file. String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(eTag)) { try { long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid. if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) { ranges.add(full); } } catch (IllegalArgumentException ignore) { ranges.add(full); } } // If any valid If-Range header, then process each part of byte range. if (ranges.isEmpty()) { for (String part : range.substring(6).split(",")) { // Assuming a file with length of 100, the following examples returns bytes at: // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100). long start = sublong(part, 0, part.indexOf("-")); long end = sublong(part, part.indexOf("-") + 1, part.length()); if (start == -1) { start = length - end; end = length - 1; } else if (end == -1 || end > length - 1) { end = length - 1; } // Check if Range is syntactically valid. If not, then return 416. if (start > end) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // Add range. ranges.add(new Range(start, end, length)); } } } // Prepare and initialize response -------------------------------------------------------- // Get content type by file name and set default GZIP support and content disposition. String contentType = getServletContext().getMimeType(fileName); boolean acceptsGzip = false; String disposition = "inline"; // If content type is unknown, then set the default value. // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp // To add new content types, add new mime-mapping entry in web.xml. if (contentType == null) { contentType = "text/plain"; } // If content type is text, then determine whether GZIP content encoding is supported by // the browser and expand content type with the one and right character encoding. // Else, expect for images, determine content disposition. If content type is supported by // the browser, then set to inline, else attachment which will pop a 'save as' dialogue. if (contentType.startsWith("text")) { String acceptEncoding = request.getHeader("Accept-Encoding"); acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip"); contentType += ";charset=UTF-8"; } else if (!contentType.startsWith("image")) { String accept = request.getHeader("Accept"); disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment"; } // Initialize response. response.reset(); response.setBufferSize(DEFAULT_BUFFER_SIZE); response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", eTag); response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME); // Send requested file (part(s)) to client ------------------------------------------------ // Prepare streams. RandomAccessFile input = null; OutputStream output = null; try { // Open streams. input = new RandomAccessFile(file, "r"); output = response.getOutputStream(); if (ranges.isEmpty() || ranges.get(0) == full) { // Return full file. Range r = full; response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); if (content) { if (acceptsGzip) { // The browser accepts GZIP, so GZIP the content. response.setHeader("Content-Encoding", "gzip"); output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE); } else { // Content length is not directly predictable in case of GZIP. // So only add it if there is no means of GZIP, else browser will hang. response.setHeader("Content-Length", String.valueOf(r.length)); } // Copy full range. copy(input, output, r.start, r.length); } } else if (ranges.size() == 1) { // Return single part of file. Range r = ranges.get(0); response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); response.setHeader("Content-Length", String.valueOf(r.length)); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Copy single part range. copy(input, output, r.start, r.length); } } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Cast back to ServletOutputStream to get the easy println methods. ServletOutputStream sos = (ServletOutputStream) output; // Copy multi part range. for (Range r : ranges) { // Add multipart boundary and header fields for every range. sos.println(); sos.println("--" + MULTIPART_BOUNDARY); sos.println("Content-Type: " + contentType); sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total); // Copy single part range of multi part range. copy(input, output, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + MULTIPART_BOUNDARY + "--"); } } } finally { // Gently close streams. close(output); close(input); } }
From source file:eionet.eunis.servlets.DownloadServlet.java
/** * Process the actual request.//from w w w .j ava 2 s . c o m * * @param request The request to be processed. * @param response The response to be created. * @param content Whether the request body should be written (GET) or not (HEAD). * @throws IOException If something fails at I/O level. * @throws ServletException */ private void processRequest(HttpServletRequest request, HttpServletResponse response, boolean content) throws IOException, ServletException { String requestURI = request.getRequestURI(); String contextPath = request.getContextPath(); String pathInfo = request.getPathInfo(); String servletPath = request.getServletPath(); // Create the abstract file reference to the requested file. File file = null; String fileRelativePath = StringUtils.substringAfter(request.getRequestURI(), request.getContextPath()); fileRelativePath = StringUtils.replace(fileRelativePath, "%20", " "); if (StringUtils.isNotEmpty(fileRelativePath) && StringUtils.isNotEmpty(appHome)) { file = new File(appHome, fileRelativePath); } // If file was not found, send 404. if (file == null || !file.exists() || file.isDirectory()) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return; } // Prepare some variables. The ETag is an unique identifier of the file. String fileName = file.getName(); long length = file.length(); long lastModified = file.lastModified(); String eTag = fileName + "_" + length + "_" + lastModified; // Validate request headers for caching --------------------------------------------------- // If-None-Match header should contain "*" or ETag. If so, then return 304. String ifNoneMatch = request.getHeader("If-None-Match"); if (ifNoneMatch != null && matches(ifNoneMatch, eTag)) { response.setHeader("ETag", eTag); // Required in 304. response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } // If-Modified-Since header should be greater than LastModified. If so, then return 304. // This header is ignored if any If-None-Match header is specified. long ifModifiedSince = request.getDateHeader("If-Modified-Since"); if (ifNoneMatch == null && ifModifiedSince != -1 && ifModifiedSince + 1000 > lastModified) { response.setHeader("ETag", eTag); // Required in 304. response.sendError(HttpServletResponse.SC_NOT_MODIFIED); return; } // Validate request headers for resume ---------------------------------------------------- // If-Match header should contain "*" or ETag. If not, then return 412. String ifMatch = request.getHeader("If-Match"); if (ifMatch != null && !matches(ifMatch, eTag)) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // If-Unmodified-Since header should be greater than LastModified. If not, then return 412. long ifUnmodifiedSince = request.getDateHeader("If-Unmodified-Since"); if (ifUnmodifiedSince != -1 && ifUnmodifiedSince + 1000 <= lastModified) { response.sendError(HttpServletResponse.SC_PRECONDITION_FAILED); return; } // Validate and process range ------------------------------------------------------------- // Prepare some variables. The full Range represents the complete file. Range full = new Range(0, length - 1, length); List<Range> ranges = new ArrayList<Range>(); // Validate and process Range and If-Range headers. String range = request.getHeader("Range"); if (range != null) { // Range header should match format "bytes=n-n,n-n,n-n...". If not, then return 416. if (!range.matches("^bytes=\\d*-\\d*(,\\d*-\\d*)*$")) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // If-Range header should either match ETag or be greater then LastModified. If not, // then return full file. String ifRange = request.getHeader("If-Range"); if (ifRange != null && !ifRange.equals(eTag)) { try { long ifRangeTime = request.getDateHeader("If-Range"); // Throws IAE if invalid. if (ifRangeTime != -1 && ifRangeTime + 1000 < lastModified) { ranges.add(full); } } catch (IllegalArgumentException ignore) { ranges.add(full); } } // If any valid If-Range header, then process each part of byte range. if (ranges.isEmpty()) { for (String part : range.substring(6).split(",")) { // Assuming a file with length of 100, the following examples returns bytes at: // 50-80 (50 to 80), 40- (40 to length=100), -20 (length-20=80 to length=100). long start = sublong(part, 0, part.indexOf("-")); long end = sublong(part, part.indexOf("-") + 1, part.length()); if (start == -1) { start = length - end; end = length - 1; } else if (end == -1 || end > length - 1) { end = length - 1; } // Check if Range is syntactically valid. If not, then return 416. if (start > end) { response.setHeader("Content-Range", "bytes */" + length); // Required in 416. response.sendError(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE); return; } // Add range. ranges.add(new Range(start, end, length)); } } } // Prepare and initialize response -------------------------------------------------------- // Get content type by file name and set default GZIP support and content disposition. String contentType = getServletContext().getMimeType(fileName); boolean acceptsGzip = false; String disposition = "inline"; // If content type is unknown, then set the default value. // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp // To add new content types, add new mime-mapping entry in web.xml. if (contentType == null) { contentType = "application/octet-stream"; } // If content type is text, then determine whether GZIP content encoding is supported by // the browser and expand content type with the one and right character encoding. // Else, expect for images, determine content disposition. If content type is supported by // the browser, then set to inline, else attachment which will pop a 'save as' dialogue. if (contentType.startsWith("text")) { String acceptEncoding = request.getHeader("Accept-Encoding"); acceptsGzip = acceptEncoding != null && accepts(acceptEncoding, "gzip"); contentType += ";charset=UTF-8"; } else if (!contentType.startsWith("image")) { String accept = request.getHeader("Accept"); disposition = accept != null && accepts(accept, contentType) ? "inline" : "attachment"; } // Initialize response. response.reset(); response.setBufferSize(DEFAULT_BUFFER_SIZE); response.setHeader("Content-Disposition", disposition + ";filename=\"" + fileName + "\""); response.setHeader("Accept-Ranges", "bytes"); response.setHeader("ETag", eTag); response.setDateHeader("Last-Modified", lastModified); response.setDateHeader("Expires", System.currentTimeMillis() + DEFAULT_EXPIRE_TIME); // Send requested file (part(s)) to client ------------------------------------------------ // Prepare streams. RandomAccessFile input = null; OutputStream output = null; try { // Open streams. input = new RandomAccessFile(file, "r"); output = response.getOutputStream(); if (ranges.isEmpty() || ranges.get(0) == full) { // Return full file. Range r = full; response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); if (content) { if (acceptsGzip) { // The browser accepts GZIP, so GZIP the content. response.setHeader("Content-Encoding", "gzip"); output = new GZIPOutputStream(output, DEFAULT_BUFFER_SIZE); } else { // Content length is not directly predictable in case of GZIP. // So only add it if there is no means of GZIP, else browser will hang. response.setHeader("Content-Length", String.valueOf(r.length)); } // Copy full range. copy(input, output, r.start, r.length); } } else if (ranges.size() == 1) { // Return single part of file. Range r = ranges.get(0); response.setContentType(contentType); response.setHeader("Content-Range", "bytes " + r.start + "-" + r.end + "/" + r.total); response.setHeader("Content-Length", String.valueOf(r.length)); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Copy single part range. copy(input, output, r.start, r.length); } } else { // Return multiple parts of file. response.setContentType("multipart/byteranges; boundary=" + MULTIPART_BOUNDARY); response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); // 206. if (content) { // Cast back to ServletOutputStream to get the easy println methods. ServletOutputStream sos = (ServletOutputStream) output; // Copy multi part range. for (Range r : ranges) { // Add multipart boundary and header fields for every range. sos.println(); sos.println("--" + MULTIPART_BOUNDARY); sos.println("Content-Type: " + contentType); sos.println("Content-Range: bytes " + r.start + "-" + r.end + "/" + r.total); // Copy single part range of multi part range. copy(input, output, r.start, r.length); } // End with multipart boundary. sos.println(); sos.println("--" + MULTIPART_BOUNDARY + "--"); } } } finally { // Gently close streams. close(output); close(input); } }
From source file:org.sakaiproject.calendar.impl.BaseCalendarService.java
protected void handleAccessPdf(HttpServletRequest req, HttpServletResponse res, Reference ref, String calRef) throws EntityPermissionException, EntityNotDefinedException { try {//from w w w . j av a2s . co m Properties options = new Properties(); Enumeration e = req.getParameterNames(); while (e.hasMoreElements()) { String key = (String) e.nextElement(); String[] values = req.getParameterValues(key); if (values.length == 1) { options.put(key, values[0]); } else { StringBuilder buf = new StringBuilder(); for (int i = 0; i < values.length; i++) { buf.append(values[i] + "^"); } options.put(key, buf.toString()); } } // We need to write to a temporary stream for better speed, plus // so we can get a byte count. Internet Explorer has problems // if we don't make the setContentLength() call. ByteArrayOutputStream outByteStream = new ByteArrayOutputStream(); res.addHeader("Content-Disposition", "inline; filename=\"schedule.pdf\""); res.setContentType(PDF_MIME_TYPE); printSchedule(options, outByteStream); res.setContentLength(outByteStream.size()); if (outByteStream.size() > 0) { // Increase the buffer size for more speed. res.setBufferSize(outByteStream.size()); } OutputStream out = null; try { out = res.getOutputStream(); if (outByteStream.size() > 0) { outByteStream.writeTo(out); } out.flush(); out.close(); } catch (Throwable ignore) { } finally { if (out != null) { try { out.close(); } catch (Throwable ignore) { } } } } catch (Throwable t) { throw new EntityNotDefinedException(ref.getReference()); } }
From source file:com.admc.jcreole.CreoleToHtmlHandler.java
public void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { File css;/*from w ww .jav a2 s . co m*/ URL url; StringBuilder readmeSb = null; File fsDirFile = null; List<String> cssHrefs = new ArrayList<String>(); File servletPathFile = new File(req.getServletPath()); if (contextPath == null) { contextPath = application.getContextPath(); iwUrls.put("home", contextPath); String appName = application.getServletContextName(); iwLabels.put("home", ((appName == null) ? "Site" : appName) + " Home Page"); } InputStream bpStream = null; Matcher matcher = servletFilePattern.matcher(servletPathFile.getName()); if (!matcher.matches()) throw new ServletException("Servlet " + getClass().getName() + " only supports servlet paths ending with '.html': " + servletPathFile.getAbsolutePath()); File crRootedDir = servletPathFile.getParentFile(); // crRootedDir is the parent dir of the requested path. String pageBaseName = matcher.group(1); String absUrlDirPath = contextPath + crRootedDir.getAbsolutePath(); String absUrlBasePath = absUrlDirPath + '/' + pageBaseName; File creoleFile = new File((isRootAbsolute ? "" : "/") + creoleRoot + crRootedDir.getAbsolutePath(), pageBaseName + ".creole"); // creoleFile is a /-path either absolute or CR-rooted InputStream creoleStream = null; creoleStream = isRootAbsolute ? (creoleFile.isFile() ? new FileInputStream(creoleFile) : null) : application.getResourceAsStream(creoleFile.getAbsolutePath()); if (indexer != null) { if (isRootAbsolute) { fsDirFile = creoleFile.getParentFile(); if (!fsDirFile.isDirectory()) fsDirFile = null; } else { fsDirFile = new File(application.getRealPath(creoleFile.getParentFile().getAbsolutePath())); } if (fsDirFile != null && !fsDirFile.isDirectory()) throw new ServletException( "fsDirFile unexpectedly not a directory: " + fsDirFile.getAbsolutePath()); } if (pageBaseName.equals("index")) { File readmeFile = new File(creoleFile.getParentFile(), "readme.creole"); InputStream readmeStream = isRootAbsolute ? (readmeFile.isFile() ? new FileInputStream(readmeFile) : null) : application.getResourceAsStream(readmeFile.getAbsolutePath()); readmeSb = new StringBuilder("----\n"); if (readmeStream == null) { readmeSb.append("{{{\n"); readmeStream = application .getResourceAsStream(new File(crRootedDir, "readme.txt").getAbsolutePath()); if (readmeStream != null) { readmeSb.append(IOUtil.toStringBuilder(readmeStream)); readmeSb.append("\n}}}\n"); } } else { readmeSb.append(IOUtil.toStringBuilder(readmeStream)); } if (readmeStream == null) readmeSb = null; } boolean inAncestorDir = false; File tmpDir; tmpDir = crRootedDir; while (tmpDir != null) { // Search from crRootedDir to creoleRoot for auxilliary files File curDir = new File((isRootAbsolute ? "" : "/") + creoleRoot + tmpDir.getAbsolutePath()); File bpFile = new File(curDir, "boilerplate.html"); if (bpStream == null) bpStream = isRootAbsolute ? (bpFile.isFile() ? new FileInputStream(bpFile) : null) : application.getResourceAsStream(bpFile.getAbsolutePath()); url = application.getResource(new File(tmpDir, "site.css").getAbsolutePath()); if (url != null) cssHrefs.add(0, new File(contextPath + tmpDir, "site.css").getAbsolutePath()); if (creoleStream == null && inAncestorDir && pageBaseName.equals("index") && autoIndexing) { File indexFile = new File(curDir, "index.creole"); creoleStream = isRootAbsolute ? (indexFile.isFile() ? new FileInputStream(indexFile) : null) : application.getResourceAsStream(indexFile.getAbsolutePath()); } tmpDir = tmpDir.getParentFile(); inAncestorDir = true; } if (creoleStream == null) throw new ServletException("Failed to access: " + creoleFile.getAbsolutePath()); if (bpStream == null) throw new ServletException("Failed to access 'boilerplate.html' " + "from creole dir or ancestor dir"); tmpDir = crRootedDir; while (tmpDir != null) { url = application.getResource(new File(tmpDir, "jcreole.css").getAbsolutePath()); if (url != null) cssHrefs.add(0, new File(contextPath + tmpDir, "jcreole.css").getAbsolutePath()); tmpDir = tmpDir.getParentFile(); } JCreole jCreole = new JCreole(IOUtil.toString(bpStream)); Expander htmlExpander = jCreole.getHtmlExpander(); Date now = new Date(); htmlExpander.put("isoDateTime", isoDateTimeFormatter.format(now), false); htmlExpander.put("isoDate", isoDateFormatter.format(now), false); htmlExpander.put("contextPath", contextPath, false); htmlExpander.put("pageBaseName", pageBaseName, false); htmlExpander.put("pageDirPath", absUrlDirPath, false); htmlExpander.put("pageTitle", absUrlBasePath, false); if (readmeSb == null) { htmlExpander.put("readmeContent", ""); } else { JCreole readmeJCreole = new JCreole(); readmeJCreole.setHtmlExpander(htmlExpander); readmeJCreole.setInterWikiMapper(this); readmeJCreole.setPrivileges(jcreolePrivs); htmlExpander.put("readmeContent", readmeJCreole.postProcess(readmeJCreole.parseCreole(readmeSb), "\n"), false); } if (fsDirFile != null) { FileComparator.SortBy sortBy = FileComparator.SortBy.NAME; boolean ascending = true; String sortStr = req.getParameter("sort"); if (sortStr != null) { Matcher m = sortParamPattern.matcher(sortStr); if (!m.matches()) throw new ServletException("Malformatted sort value: " + sortStr); ascending = m.group(1).equals("+"); try { sortBy = Enum.valueOf(FileComparator.SortBy.class, m.group(2)); } catch (Exception e) { throw new ServletException("Malformatted sort string: " + sortStr); } } htmlExpander.put("index", "\n" + indexer.generateTable(fsDirFile, absUrlDirPath, true, sortBy, ascending), false); // An alternative for using the Tomcat-like Indexer in a // htmlExpander would be to write a Creole table to a // creoleExpander. } /* Set up Creole macros like this: Expander creoleExpander = new Expander(Expander.PairedDelims.RECTANGULAR); creoleExpander.put("testMacro", "\n\n<<prettyPrint>>\n{{{\n" + "!/bin/bash -p\n\ncp /etc/inittab /tmp\n}}}\n"); jCreole.setCreoleExpander(creoleExpander); */ if (cssHrefs.size() > 0) jCreole.addCssHrefs(cssHrefs); jCreole.setInterWikiMapper(this); jCreole.setPrivileges(jcreolePrivs); String html = jCreole.postProcess(jCreole.parseCreole(IOUtil.toStringBuilder(creoleStream)), "\n"); resp.setBufferSize(1024); resp.setContentType("text/html"); resp.getWriter().print(html); }
From source file:org.jahia.services.content.files.FileServlet.java
@Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { long timer = System.currentTimeMillis(); int code = HttpServletResponse.SC_OK; try {//w ww . j ava2 s .co m FileKey fileKey = parseKey(req); if (fileKey != null && fileKey.getWorkspace() != null && StringUtils.isNotEmpty(fileKey.getPath())) { Cache<String, FileLastModifiedCacheEntry> lastModifiedCache = cacheManager.getLastModifiedCache(); FileLastModifiedCacheEntry lastModifiedEntry = lastModifiedCache.get(fileKey.getCacheKey()); if (isNotModified(fileKey, lastModifiedEntry, req, res)) { // resource is not changed code = HttpServletResponse.SC_NOT_MODIFIED; res.setStatus(HttpServletResponse.SC_NOT_MODIFIED); logAccess(fileKey, req, "ok-not-modified"); return; } Cache<String, Map<String, FileCacheEntry>> contentCache = cacheManager.getContentCache(); Map<String, FileCacheEntry> entries = contentCache.get(fileKey.getCacheKey()); FileCacheEntry fileEntry = entries != null ? entries.get(fileKey.getThumbnail()) : null; if (fileEntry == null) { JCRNodeWrapper n = getNode(fileKey); if (n == null || !n.isFile()) { // cannot find it or it is not a file code = HttpServletResponse.SC_NOT_FOUND; res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } Date lastModifiedDate = n.getLastModifiedAsDate(); long lastModified = lastModifiedDate != null ? lastModifiedDate.getTime() : 0; String eTag = generateETag(n.getIdentifier(), lastModified); if (lastModifiedEntry == null) { lastModifiedEntry = new FileLastModifiedCacheEntry(eTag, lastModified); if (canCache(n)) { lastModifiedCache.put(fileKey.getCacheKey(), lastModifiedEntry); } } if (isNotModified(fileKey, lastModifiedEntry, req, res)) { // resource is not changed code = HttpServletResponse.SC_NOT_MODIFIED; res.setStatus(HttpServletResponse.SC_NOT_MODIFIED); logAccess(fileKey, req, "ok-not-modified"); return; } fileEntry = getFileEntry(fileKey, n, lastModifiedEntry); if (fileEntry != null && fileEntry.getData() != null) { entries = contentCache.get(fileKey.getCacheKey()); if (entries == null) { entries = new HashMap<String, FileCacheEntry>(1); } entries.put(fileKey.getThumbnail(), fileEntry); contentCache.put(fileKey.getCacheKey(), entries); logAccess(fileKey, req, "ok"); } } else { if (lastModifiedEntry == null) { lastModifiedEntry = new FileLastModifiedCacheEntry(fileEntry.getETag(), fileEntry.getLastModified()); lastModifiedCache.put(fileKey.getCacheKey(), lastModifiedEntry); } logAccess(fileKey, req, "ok-cached"); if (logger.isDebugEnabled()) { logger.debug("Serving cached file entry {}", fileKey.toString()); } } if (fileEntry != null) { List<RangeUtils.Range> ranges; boolean useRanges = true; if (fileEntry.getBinary() instanceof BinaryRangesSupport) { useRanges = ((BinaryRangesSupport) fileEntry.getBinary()).supportRanges(); } ranges = useRanges ? RangeUtils.parseRange(req, res, fileEntry.getETag(), fileEntry.getLastModified(), fileEntry.getContentLength()) : null; if (fileKey.getPath().indexOf('%', fileKey.getPath().lastIndexOf('/')) != -1) { res.setHeader("Content-Disposition", "inline; filename=\"" + JCRContentUtils.unescapeLocalNodeName( StringUtils.substringAfterLast(fileKey.getPath(), "/")) + "\""); } res.setDateHeader("Last-Modified", fileEntry.getLastModified()); res.setHeader("ETag", fileEntry.getETag()); InputStream is = null; if (fileEntry.getData() != null) { // writing in-memory data is = new ByteArrayInputStream(fileEntry.getData()); } else if (fileEntry.getBinary() != null) { // spool from an input stream is = fileEntry.getBinary().getStream(); } else { code = HttpServletResponse.SC_NOT_FOUND; res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } if (ranges == null || (ranges == RangeUtils.FULL)) { res.setContentType(fileEntry.getMimeType()); if (fileEntry.getContentLength() <= Integer.MAX_VALUE) { res.setContentLength((int) fileEntry.getContentLength()); } else { res.setHeader("Content-Length", Long.toString(fileEntry.getContentLength())); } ServletOutputStream os = res.getOutputStream(); IOUtils.copy(is, os); os.flush(); os.close(); } else { res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); if (ranges.size() == 1) { res.setContentType(fileEntry.getMimeType()); RangeUtils.Range range = (RangeUtils.Range) ranges.get(0); res.addHeader("Content-Range", "bytes " + range.start + "-" + range.end + "/" + range.length); long length = range.end - range.start + 1; if (length < Integer.MAX_VALUE) { res.setContentLength((int) length); } else { // Set the content-length as String to be able to use a long res.setHeader("Content-Length", "" + length); } ServletOutputStream os = res.getOutputStream(); RangeUtils.copy(is, os, range); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } else { res.setContentType("multipart/byteranges; boundary=" + RangeUtils.MIME_SEPARATION); try { res.setBufferSize(RangeUtils.getOutput()); } catch (IllegalStateException e) { // Silent catch } ServletOutputStream os = res.getOutputStream(); RangeUtils.copy(is, os, ranges.iterator(), fileEntry.getMimeType()); IOUtils.closeQuietly(is); IOUtils.closeQuietly(os); } } if ((fileEntry.getData() == null) && (fileEntry.getBinary() != null)) { fileEntry.getBinary().dispose(); fileEntry.setBinary(null); } SpringContextSingleton.getInstance() .publishEvent(new FileDownloadEvent(this, req, fileEntry.getIdentifier(), fileKey.getPath(), fileEntry.getNodeTypes(), fileKey.getWorkspace())); } else { code = HttpServletResponse.SC_NOT_FOUND; res.sendError(HttpServletResponse.SC_NOT_FOUND); return; } } else { code = HttpServletResponse.SC_NOT_FOUND; res.sendError(HttpServletResponse.SC_NOT_FOUND); } } catch (RepositoryException e) { logger.error("Cannot get file", e); code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { if (logger.isDebugEnabled()) { logger.debug("Served [{}] with status code [{}] in [{}ms]", new Object[] { req.getRequestURI() + (req.getQueryString() != null ? "?" + req.getQueryString() : ""), code, (System.currentTimeMillis() - timer) }); } } }