1 package com.quadcap.http.servlets.file; 2 3 40 41 import java.io.File ; 42 import java.io.FileInputStream ; 43 import java.io.FileNotFoundException ; 44 import java.io.IOException ; 45 import java.io.OutputStream ; 46 47 import java.util.Enumeration ; 48 import java.util.Hashtable ; 49 50 import java.net.MalformedURLException ; 51 import java.net.URL ; 52 53 import javax.servlet.ServletConfig ; 54 import javax.servlet.ServletContext ; 55 import javax.servlet.ServletException ; 56 57 import javax.servlet.http.HttpServlet ; 58 import javax.servlet.http.HttpServletRequest ; 59 import javax.servlet.http.HttpServletResponse ; 60 61 import com.quadcap.util.Debug; 62 63 73 74 public class FileServlet extends HttpServlet { 75 76 Hashtable mimeTypes = new Hashtable (); 77 ServletContext context; 78 79 FileCache files; 80 81 88 public void init(ServletConfig config) throws ServletException { 89 super.init(config); 90 context = config.getServletContext(); 91 String s = config.getInitParameter("cacheSize"); 92 if (s == null) s = "128"; 93 files = new FileCache(this, Integer.parseInt(s)); 94 } 95 96 107 protected void service(HttpServletRequest req, HttpServletResponse res) 108 throws ServletException , IOException 109 { 110 try { 111 HttpFile file = getFileForRequest(req); 112 if (file == null) { 113 res.sendError(HttpServletResponse.SC_NOT_FOUND, 114 "Not Found"); 115 } else { 116 try { 117 file.service(req, res); 118 } catch (FileNotFoundException ex) { 119 res.sendError(HttpServletResponse.SC_NOT_FOUND, 120 "Not Found"); 121 } 122 123 } 124 } catch (FileNotFoundException f3) { 125 res.sendError(HttpServletResponse.SC_NOT_FOUND, 126 "Not Found"); 127 } catch (Exception e) { 128 Debug.print(e); 129 res.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 130 e.toString()); 131 } 132 } 133 134 143 public HttpFile getFileForRequest(HttpServletRequest req) 144 throws Exception 145 { 146 HttpFile f = null; 147 String path = req.getServletPath(); 148 String p = req.getPathInfo(); 149 if (p != null) path = path + p; 150 String real = context.getRealPath(path); 151 if (real != null) { 152 f = (HttpFile)files.get(real); if (f != null) { 154 f.checkModified(); 155 } 156 } 157 return f; 158 } 159 160 final URL getURL(String path) throws MalformedURLException { 161 return context.getResource(path); 162 } 163 164 final String getContentType(String path) { 165 return context.getMimeType(path); 166 } 167 168 } 169 | Popular Tags |