001    package org.shiftone.jrat.http;
002    
003    import org.shiftone.jrat.util.log.Logger;
004    
005    import java.io.Writer;
006    import java.util.Iterator;
007    import java.util.SortedMap;
008    import java.util.TreeMap;
009    
010    /**
011     * @author jeff@shiftone.org (Jeff Drost)
012     */
013    public class Dispatcher implements Handler {
014    
015        private static final Logger LOG = Logger.getLogger(Dispatcher.class);
016        private String title;
017        private SortedMap contexts = new TreeMap(); /* <String, Handler> */
018    
019        public Dispatcher(String title) {
020            this.title = title;
021        }
022    
023        public void addRoute(String path, Handler handler) {
024            contexts.put(path, handler);
025        }
026    
027        public void handle(Request request, Response response) throws Exception {
028    
029            //LOG.info("handle");
030    
031            String path = request.getRequestUri();
032            if (path.length() > 0 && path.charAt(0) == '/') {
033                path = path.substring(1);
034            }
035    
036            int firstSlash = path.indexOf("/");
037            String firstPart = (firstSlash == -1)
038                    ? path
039                    : path.substring(0, firstSlash);
040    
041            //LOG.info("firstPart = " + firstPart);
042            Handler handler = (Handler) contexts.get(firstPart);
043    
044            if (handler != null) {
045    
046                // trim the firstPart off the URI
047                request.setRequestUri(path.substring(firstPart.length()));
048                handler.handle(request, response);
049                //return;
050    
051            } else if (firstPart.length() == 0) {
052    
053                listHandlers(request, response);
054    
055            } else {
056    
057                throw new HttpException(Status.STATUS_404);
058    
059            }
060    
061        }
062    
063        private void listHandlers(Request request, Response response) throws Exception {
064    
065            LOG.info("listHandlers");
066    
067            response.setContentType(ContentType.TEXT_HTML);
068    
069            Writer out = response.getWriter();
070            Iterator iterator = contexts.keySet().iterator();
071    
072            out.write("<h2>" + title + "</h2>");
073    
074            out.write("<ul>");
075            while (iterator.hasNext()) {
076                String key = (String) iterator.next();
077                out.write("<li><a href='" + key + "/'>" + key + "</a></li>");
078            }
079            out.write("</ul>");
080        }
081    
082    }