Replaced the "Restarts" class with individual restart classes.
[jsvc.git] / src / dolda / jsvc / util / Multiplexer.java
1 package dolda.jsvc.util;
2
3 import dolda.jsvc.*;
4 import java.util.*;
5
6 public class Multiplexer implements Responder {
7     private Responder def;
8     private Collection<Matcher> matchers = new LinkedList<Matcher>();
9
10     public static interface Matcher {
11         public boolean match(Request req);
12     }
13     
14     public Multiplexer(Responder def) {
15         this.def = def;
16     }
17     
18     public Multiplexer() {
19         this(new Responder() {
20                 public void respond(Request req) {
21                     throw(new StdResponse(404, "Resource not found", "The resource you requested could not be found on this server."));
22                 }
23             });
24     }
25     
26     public void file(final String path, final Responder responder) {
27         add(new Matcher() {
28                 public boolean match(Request req) {
29                     if(req.path().equals(path)) {
30                         responder.respond(req);
31                         return(true);
32                     }
33                     return(false);
34                 }
35             });
36     }
37
38     public void dir(String path, final Responder responder) {
39         final String fp = Misc.stripslashes(path, true, true);
40         add(new Matcher() {
41                 public boolean match(Request req) {
42                     if(req.path().equals(fp)) {
43                         throw(new Redirect(fp + "/"));
44                     } else if(req.path().startsWith(fp + "/")) {
45                         responder.respond(RequestWrap.chpath(req, req.path().substring(fp.length() + 1)));
46                         return(true);
47                     }
48                     return(false);
49                 }
50             });
51     }
52     
53     public void add(Matcher m) {
54         matchers.add(m);
55     }
56     
57     public void respond(Request req) {
58         for(Matcher m : matchers) {
59             if(m.match(req))
60                 return;
61         }
62         def.respond(req);
63     }
64 }