1 package org.roller.presentation; 2 3 import java.io.*; 4 import java.util.Date ; 5 6 import javax.servlet.*; 7 import javax.servlet.http.*; 8 import org.apache.commons.logging.Log; 9 import org.apache.commons.logging.LogFactory; 10 11 import org.roller.model.RollerFactory; 12 13 14 26 public class ResourceServlet extends HttpServlet 27 { 28 private static Log mLogger = 29 LogFactory.getFactory().getInstance(ResourceServlet.class); 30 31 private String upload_dir = null; 32 private ServletContext context = null; 33 34 35 36 public void init(ServletConfig config) throws ServletException { 37 super.init(config); 38 39 this.context = config.getServletContext(); 40 41 try { 42 this.upload_dir = RollerFactory.getRoller().getFileManager().getUploadDir(); 43 mLogger.debug("upload dir is ["+this.upload_dir+"]"); 44 } catch(Exception e) { mLogger.warn(e); } 45 46 } 47 48 50 public void destroy() { 51 52 } 53 54 55 59 protected void processRequest(HttpServletRequest request, HttpServletResponse response) 60 throws ServletException, IOException { 61 62 String context = request.getContextPath(); 63 String servlet = request.getServletPath(); 64 String reqURI = request.getRequestURI(); 65 66 String reqResource = reqURI.substring(servlet.length() + context.length()); 69 70 String resource_path = this.upload_dir + reqResource; 72 File resource = new File(resource_path); 73 74 mLogger.debug("Resource requested ["+reqURI+"]"); 75 mLogger.debug("Real path is ["+resource.getAbsolutePath()+"]"); 76 77 if(!resource.exists() || !resource.canRead()) { 79 response.sendError(HttpServletResponse.SC_NOT_FOUND); 80 return; 81 } 82 83 Date ifModDate = new Date (request.getDateHeader("If-Modified-Since")); 85 Date lastMod = new Date (resource.lastModified()); 86 if(lastMod.compareTo(ifModDate) <= 0) { 87 mLogger.debug("Resource unmodified ... sending 304"); 88 response.setStatus(HttpServletResponse.SC_NOT_MODIFIED); 89 return; 90 } 91 92 response.addDateHeader("Last-Modified", (new Date ()).getTime()); 96 response.setContentType(this.context.getMimeType(resource.getAbsolutePath())); 97 98 byte[] buf = new byte[8192]; 100 int length = 0; 101 OutputStream out = response.getOutputStream(); 102 InputStream resource_file = new FileInputStream(resource); 103 while((length = resource_file.read(buf)) > 0) 104 out.write(buf, 0, length); 105 } 106 107 108 112 protected void doGet(HttpServletRequest request, HttpServletResponse response) 113 throws ServletException, IOException { 114 processRequest(request, response); 115 } 116 117 121 protected void doPost(HttpServletRequest request, HttpServletResponse response) 122 throws ServletException, IOException { 123 processRequest(request, response); 124 } 125 126 128 public String getServletInfo() { 129 return "ResourceServlet ... serving you since 2005 ;)"; 130 } 131 132 } 133 | Popular Tags |