1 package freecs.external; 2 3 import java.io.File ; 4 import java.io.FileInputStream ; 5 import java.io.InputStream ; 6 import java.util.HashMap ; 7 8 import freecs.Server; 9 import freecs.content.ContentContainer; 10 import freecs.interfaces.IRequest; 11 12 public class StaticRequestHandler extends AbstractRequestHandler { 13 private HashMap fileCache = new HashMap (); 14 15 public StaticRequestHandler(String handlerName) { 16 super(handlerName); 17 } 18 19 22 23 public void handle(IRequest req, ContentContainer c) { 24 String file = req.getAction(); 25 file = file.substring(file.substring(1).indexOf("/") + 2); 26 Object cached = fileCache.get(file); 27 if (cached != null) { 28 FileProperties fp = (FileProperties) cached; 29 if (!fp.f.exists()) { 30 c.setTemplate("not_found"); 31 return; 32 } else if (fp.f.lastModified() == fp.lastModified) { 33 try { 34 c.setContent(fp.content); 35 } catch (Exception e) { 36 throw new AccessForbiddenException(true); 37 } 38 c.setContentType(fp.contentType); 39 return; 40 } 41 } 42 if (file.indexOf("/") > -1 && !file.endsWith(".class")) 43 throw new AccessForbiddenException (true); 44 File f = new File (Server.BASE_PATH + "/static/" + file); 45 if (!f.exists()) { 46 c.setTemplate("not_found"); 47 return; 48 } 49 String contentType; 50 if (file.toLowerCase().endsWith (".gif")) 51 contentType="image/gif"; 52 else if (file.toLowerCase().endsWith (".jpg") 53 || file.toLowerCase().endsWith (".jpeg")) 54 contentType="image/jpeg"; 55 else if (file.toLowerCase().endsWith (".class")) 56 contentType="application/x-java-applet"; 57 else 58 throw new AccessForbiddenException (true); 59 try { 60 InputStream is = new FileInputStream (f); 61 byte[] cntnt = new byte[(int) f.length()]; 62 for (int i = 0; i<cntnt.length; i++) 63 cntnt[i] = (byte) is.read(); 64 fileCache.put(file, new FileProperties(f, cntnt, contentType)); 65 c.setContent(cntnt); 66 } catch (Exception e) { 67 Server.debug ("StaticRequestHandler", "exception during reading file " + file, e, Server.MSG_ERROR, Server.LVL_MINOR); 68 c.setTemplate("techerror"); 69 return; 70 } 71 c.setContentType(contentType); 72 } 73 74 class FileProperties { 75 long lastModified = -1; 76 File f; 77 byte[] content; 78 String contentType; 79 80 FileProperties (File f, byte[] content, String contentType) { 81 this.f = f; 82 this.content = content; 83 this.contentType = contentType; 84 lastModified = f.lastModified(); 85 } 86 } 87 } 88 | Popular Tags |