01: package com.icesoft.faces.webapp.http.servlet;
02:
03: import org.apache.commons.logging.Log;
04: import org.apache.commons.logging.LogFactory;
05:
06: import javax.servlet.http.HttpServletRequest;
07: import javax.servlet.http.HttpServletResponse;
08: import java.util.ArrayList;
09: import java.util.Iterator;
10: import java.util.List;
11: import java.util.regex.Pattern;
12:
13: public class PathDispatcher implements PseudoServlet {
14:
15: private static Log log = LogFactory.getLog(PathDispatcher.class);
16:
17: private List matchers = new ArrayList();
18:
19: public void service(HttpServletRequest request,
20: HttpServletResponse response) throws Exception {
21: String path = request.getRequestURI();
22:
23: if (log.isDebugEnabled()) {
24: log.debug("path: " + path);
25: }
26:
27: Iterator i = matchers.iterator();
28: boolean matched = false;
29: while (!matched && i.hasNext()) {
30: matched = ((Matcher) i.next()).serviceOnMatch(path,
31: request, response);
32: }
33:
34: if (!matched) {
35: response.sendError(404, "Resource at '" + path
36: + "' not found.");
37: }
38: }
39:
40: public void dispatchOn(String pathExpression, PseudoServlet toServer) {
41: matchers.add(new Matcher(pathExpression, toServer));
42: }
43:
44: private class Matcher {
45: private Pattern pattern;
46: private PseudoServlet server;
47:
48: public Matcher(String expression, PseudoServlet server) {
49: this .pattern = Pattern.compile(expression);
50: this .server = server;
51: }
52:
53: boolean serviceOnMatch(String path, HttpServletRequest request,
54: HttpServletResponse response) throws Exception {
55: if (pattern.matcher(path).find()) {
56: server.service(request, response);
57: return true;
58: } else {
59: return false;
60: }
61: }
62:
63: void shutdown() {
64: server.shutdown();
65: }
66: }
67:
68: public void shutdown() {
69: Iterator i = matchers.iterator();
70: while (i.hasNext()) {
71: Matcher matcher = (Matcher) i.next();
72: matcher.shutdown();
73: }
74: }
75: }
|