Commit | Line | Data |
---|---|---|
79d2dd64 FT |
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; | |
18a28994 | 8 | private Collection<Matcher> matchers = new LinkedList<Matcher>(); |
79d2dd64 | 9 | |
18a28994 FT |
10 | public static interface Matcher { |
11 | public boolean match(Request req); | |
79d2dd64 FT |
12 | } |
13 | ||
14 | public Multiplexer(Responder def) { | |
15 | this.def = def; | |
16 | } | |
17 | ||
18 | public Multiplexer() { | |
7779099a FT |
19 | this(new Responder() { |
20 | public void respond(Request req) { | |
21 | throw(Restarts.stdresponse(404, "Resource not found", "The resource you requested could not be found on this server.")); | |
79d2dd64 FT |
22 | } |
23 | }); | |
24 | } | |
25 | ||
26 | public void file(final String path, final Responder responder) { | |
18a28994 | 27 | add(new Matcher() { |
79d2dd64 FT |
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); | |
18a28994 | 40 | add(new Matcher() { |
79d2dd64 FT |
41 | public boolean match(Request req) { |
42 | if(req.path().equals(fp)) { | |
43 | throw(Restarts.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 | ||
18a28994 FT |
53 | public void add(Matcher m) { |
54 | matchers.add(m); | |
55 | } | |
56 | ||
79d2dd64 | 57 | public void respond(Request req) { |
18a28994 FT |
58 | for(Matcher m : matchers) { |
59 | if(m.match(req)) | |
79d2dd64 FT |
60 | return; |
61 | } | |
62 | def.respond(req); | |
63 | } | |
64 | } |