1 package com.genimen.djeneric.web; 2 3 import java.io.IOException ; 4 import java.text.SimpleDateFormat ; 5 import java.util.Date ; 6 import java.util.Locale ; 7 import java.util.TimeZone ; 8 9 import javax.servlet.ServletContext ; 10 import javax.servlet.ServletException ; 11 import javax.servlet.http.HttpServletRequest ; 12 import javax.servlet.http.HttpServletResponse ; 13 14 import com.genimen.djeneric.repository.exceptions.DjenericException; 15 import com.genimen.djeneric.structure.ResourceDefinition; 16 import com.genimen.djeneric.web.controller.DjenericController; 17 import com.genimen.djeneric.web.util.DjenericServlet; 18 import com.genimen.djeneric.web.util.DjenericSessionManager; 19 20 24 public class ResourceServlet extends DjenericServlet 25 { 26 private static final long serialVersionUID = 1L; 27 public static final String HTTP_RESPONSE_DATE_HEADER = "EEE, dd MMM yyyy HH:mm:ss zzz"; 28 private static SimpleDateFormat DATE_FORMAT; 29 long _lastmodified = System.currentTimeMillis(); 30 private int _expirySeconds = 60 * 60 * 24; 31 32 public ResourceServlet() 33 { 34 DATE_FORMAT = new SimpleDateFormat (HTTP_RESPONSE_DATE_HEADER, Locale.US); 35 DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("GMT")); 36 } 37 38 public long getLastModified(HttpServletRequest req) 39 { 40 return _lastmodified; 41 } 42 43 public void enableBrowserCaching(HttpServletResponse response) 44 { 45 response.setHeader("Cache-Control", "max-age=" + String.valueOf(_expirySeconds) + ", " + "s-max-age=" 46 + String.valueOf(_expirySeconds) 47 + ", public, must-revalidate, proxy-revalidate"); 48 response.setHeader("Expires", DATE_FORMAT.format(new Date (System.currentTimeMillis() + _expirySeconds * 1000))); 49 } 50 51 public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException , IOException 52 { 53 enableBrowserCaching(resp); 54 String fileName = req.getPathInfo().toString(); 55 56 DjenericSessionManager mgr = (DjenericSessionManager) req.getSession() 57 .getAttribute(DjenericController.DJENERIC_SESSION_MANAGER); 58 ResourceDefinition res = null; 59 if (mgr != null) 60 { 61 try 62 { 63 res = mgr.getResource(fileName); 64 } 65 catch (DjenericException e) 66 { 67 throw new ServletException (e); 68 } 69 } 70 71 if (res == null) 72 { 73 resp.sendError(404); 74 } 75 else 76 { 77 resp.setContentType(getContentType(fileName)); 78 resp.getOutputStream().write(res.getBytes()); 79 } 80 } 81 82 private String getContentType(String fileName) 83 { 84 ServletContext sc = getServletContext(); 85 String type = sc.getMimeType(fileName); 86 if (type == null) type = "text/plain"; 87 return type; 88 } 89 90 } | Popular Tags |