1 13 package info.magnolia.cms.servlets; 14 15 import info.magnolia.cms.core.Path; 16 17 import java.io.File ; 18 import java.io.FileInputStream ; 19 import java.io.IOException ; 20 21 import javax.servlet.ServletOutputStream ; 22 import javax.servlet.http.HttpServlet ; 23 import javax.servlet.http.HttpServletRequest ; 24 import javax.servlet.http.HttpServletResponse ; 25 26 import org.apache.log4j.Logger; 27 28 29 34 public class Spool extends HttpServlet { 35 36 39 private static final long serialVersionUID = 222L; 40 41 44 private static Logger log = Logger.getLogger(Spool.class); 45 46 51 public long getLastModified(HttpServletRequest request) { 52 File resource = new File (getServletContext().getRealPath(Path.getURI(request))); 53 if (resource.exists()) { 54 return resource.lastModified(); 55 } 56 return -1; 57 } 58 59 65 public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException { 66 File resource = new File (getServletContext().getRealPath(Path.getURI(request))); 67 if (!resource.exists() || resource.isDirectory()) { 68 response.sendError(HttpServletResponse.SC_NOT_FOUND); 69 return; 70 } 71 this.setResponseHeaders(resource, response); 72 boolean success = this.spool(resource, response); 73 if (!success && !response.isCommitted()) { 74 response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); 75 } 76 } 77 78 84 private boolean spool(File resource, HttpServletResponse response) throws IOException { 85 FileInputStream in = new FileInputStream (resource); 86 87 try { 88 ServletOutputStream os = response.getOutputStream(); 89 byte[] buffer = new byte[8192]; 90 int read = 0; 91 while ((read = in.read(buffer)) > 0) { 92 os.write(buffer, 0, read); 93 } 94 os.flush(); 95 os.close(); 96 } 97 catch (IOException e) { 98 log.debug("Unable to spool resource due to a " + e.getClass().getName() + " exception", e); return false; 102 } 103 finally { 104 try { 105 in.close(); 106 } 107 catch (Exception e) { 108 } 110 } 111 return true; 112 } 113 114 119 private void setResponseHeaders(File resource, HttpServletResponse response) { 120 response.setContentLength((int) resource.length()); 121 } 122 123 } 124 | Popular Tags |