Made cache checking easier.
[jsvc.git] / src / dolda / jsvc / util / StaticContent.java
1 package dolda.jsvc.util;
2
3 import dolda.jsvc.*;
4 import java.io.*;
5 import java.util.*;
6
7 public class StaticContent implements Responder {
8     private final Class<?> base;
9     private final String resname;
10     private final boolean dir;
11     private final String mimetype;
12     
13     public StaticContent(Class<?> base, String resname, boolean dir, String mimetype) {
14         this.base = base;
15         this.resname = resname;
16         this.dir = dir;
17         this.mimetype = mimetype;
18     }
19     
20     public StaticContent(String resname, boolean dir, String mimetype) {
21         this(null, resname, dir, mimetype);
22     }
23     
24     public void respond(Request req) {
25         String nm;
26         if(dir) {
27             nm = resname + "/" + req.path();
28         } else {
29             nm = resname;
30         }
31         InputStream in;
32         if(base == null) {
33             in = StaticContent.class.getClassLoader().getResourceAsStream(nm);
34         } else {
35             in = base.getResourceAsStream(nm);
36         }
37         if(in == null)
38             throw(Restarts.stdresponse(404));
39         Cache.checkmtime(req, req.ctx().starttime());
40         try {
41             try {
42                 req.outheaders().put("Content-Type", mimetype);
43                 Misc.cpstream(in, req.output());
44             } finally {
45                 in.close();
46             }
47         } catch(IOException e) {
48             throw(new Error(e));
49         }
50     }
51 }