1   // ========================================================================
2   // Copyright 1999-2005 Mort Bay Consulting Pty. Ltd.
3   // ------------------------------------------------------------------------
4   // Licensed under the Apache License, Version 2.0 (the "License");
5   // you may not use this file except in compliance with the License.
6   // You may obtain a copy of the License at 
7   // http://www.apache.org/licenses/LICENSE-2.0
8   // Unless required by applicable law or agreed to in writing, software
9   // distributed under the License is distributed on an "AS IS" BASIS,
10  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11  // See the License for the specific language governing permissions and
12  // limitations under the License.
13  // ========================================================================
14  
15  package org.mortbay.jetty.handler;
16  
17  import java.io.IOException;
18  import java.io.OutputStream;
19  import java.net.URL;
20  
21  import javax.servlet.ServletException;
22  import javax.servlet.http.HttpServletRequest;
23  import javax.servlet.http.HttpServletResponse;
24  
25  import org.mortbay.jetty.Handler;
26  import org.mortbay.jetty.HttpConnection;
27  import org.mortbay.jetty.HttpHeaders;
28  import org.mortbay.jetty.HttpMethods;
29  import org.mortbay.jetty.MimeTypes;
30  import org.mortbay.jetty.Request;
31  import org.mortbay.jetty.Server;
32  import org.mortbay.log.Log;
33  import org.mortbay.util.ByteArrayISO8859Writer;
34  import org.mortbay.util.IO;
35  import org.mortbay.util.StringUtil;
36  
37  
38  /* ------------------------------------------------------------ */
39  /** Default Handler.
40   * 
41   * This handle will deal with unhandled requests in the server.
42   * For requests for favicon.ico, the Jetty icon is served. 
43   * For reqests to '/' a 404 with a list of known contexts is served.
44   * For all other requests a normal 404 is served.
45   * TODO Implement OPTIONS and TRACE methods for the server.
46   * 
47   * @author Greg Wilkins (gregw)
48   * @org.apache.xbean.XBean
49   */
50  public class DefaultHandler extends AbstractHandler
51  {
52      long _faviconModified=(System.currentTimeMillis()/1000)*1000;
53      byte[] _favicon;
54      boolean _serveIcon=true;
55      
56      public DefaultHandler()
57      {
58          try
59          {
60              URL fav = this.getClass().getClassLoader().getResource("org/mortbay/jetty/favicon.ico");
61              if (fav!=null)
62              _favicon=IO.readBytes(fav.openStream());
63          }
64          catch(Exception e)
65          {
66              Log.warn(e);
67          }
68      }
69      
70      /* ------------------------------------------------------------ */
71      /* 
72       * @see org.mortbay.jetty.Handler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, int)
73       */
74      public void handle(String target, HttpServletRequest request, HttpServletResponse response, int dispatch) throws IOException, ServletException
75      {      
76          Request base_request = request instanceof Request?(Request)request:HttpConnection.getCurrentConnection().getRequest();
77          
78          if (response.isCommitted() || base_request.isHandled())
79              return;
80          
81          base_request.setHandled(true);
82          
83          String method=request.getMethod();
84  
85          // little cheat for common request
86          if (_serveIcon && _favicon!=null && method.equals(HttpMethods.GET) && request.getRequestURI().equals("/favicon.ico"))
87          {
88              if (request.getDateHeader(HttpHeaders.IF_MODIFIED_SINCE)==_faviconModified)
89                  response.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
90              else
91              {
92                  response.setStatus(HttpServletResponse.SC_OK);
93                  response.setContentType("image/x-icon");
94                  response.setContentLength(_favicon.length);
95                  response.setDateHeader(HttpHeaders.LAST_MODIFIED, _faviconModified);
96                  response.setHeader(HttpHeaders.CACHE_CONTROL,"max-age=360000,public");
97                  response.getOutputStream().write(_favicon);
98              }
99              return;
100         }
101         
102         
103         if (!method.equals(HttpMethods.GET) || !request.getRequestURI().equals("/"))
104         {
105             response.sendError(HttpServletResponse.SC_NOT_FOUND);
106             return;   
107         }
108 
109         response.setStatus(HttpServletResponse.SC_NOT_FOUND);
110         response.setContentType(MimeTypes.TEXT_HTML);
111         
112         ByteArrayISO8859Writer writer = new ByteArrayISO8859Writer(1500);
113 
114         String uri=request.getRequestURI();
115         uri=StringUtil.replace(uri,"<","&lt;");
116         uri=StringUtil.replace(uri,">","&gt;");
117         
118         writer.write("<HTML>\n<HEAD>\n<TITLE>Error 404 - Not Found");
119         writer.write("</TITLE>\n<BODY>\n<H2>Error 404 - Not Found.</H2>\n");
120         writer.write("No context on this server matched or handled this request.<BR>");
121         writer.write("Contexts known to this server are: <ul>");
122 
123 
124         Server server = getServer();
125         Handler[] handlers = server==null?null:server.getChildHandlersByClass(ContextHandler.class);
126  
127         for (int i=0;handlers!=null && i<handlers.length;i++)
128         {
129             ContextHandler context = (ContextHandler)handlers[i];
130             if (context.isRunning())
131             {
132                 writer.write("<li><a href=\"");
133                 if (context.getVirtualHosts()!=null && context.getVirtualHosts().length>0)
134                     writer.write("http://"+context.getVirtualHosts()[0]+":"+request.getLocalPort());
135                 writer.write(context.getContextPath());
136                 if (context.getContextPath().length()>1 && context.getContextPath().endsWith("/"))
137                     writer.write("/");
138                 writer.write("\">");
139                 writer.write(context.getContextPath());
140                 if (context.getVirtualHosts()!=null && context.getVirtualHosts().length>0)
141                     writer.write("&nbsp;@&nbsp;"+context.getVirtualHosts()[0]+":"+request.getLocalPort());
142                 writer.write("&nbsp;--->&nbsp;");
143                 writer.write(context.toString());
144                 writer.write("</a></li>\n");
145             }
146             else
147             {
148                 writer.write("<li>");
149                 writer.write(context.getContextPath());
150                 if (context.getVirtualHosts()!=null && context.getVirtualHosts().length>0)
151                     writer.write("&nbsp;@&nbsp;"+context.getVirtualHosts()[0]+":"+request.getLocalPort());
152                 writer.write("&nbsp;--->&nbsp;");
153                 writer.write(context.toString());
154                 if (context.isFailed())
155                     writer.write(" [failed]");
156                 if (context.isStopped())
157                     writer.write(" [stopped]");
158                 writer.write("</li>\n");
159             }
160         }
161         
162         for (int i=0;i<10;i++)
163             writer.write("\n<!-- Padding for IE                  -->");
164         
165         writer.write("\n</BODY>\n</HTML>\n");
166         writer.flush();
167         response.setContentLength(writer.size());
168         OutputStream out=response.getOutputStream();
169         writer.writeTo(out);
170         out.close();
171         
172         return;
173     }
174 
175     /* ------------------------------------------------------------ */
176     /**
177      * @return Returns true if the handle can server the jetty favicon.ico
178      */
179     public boolean getServeIcon()
180     {
181         return _serveIcon;
182     }
183 
184     /* ------------------------------------------------------------ */
185     /**
186      * @param serveIcon true if the handle can server the jetty favicon.ico
187      */
188     public void setServeIcon(boolean serveIcon)
189     {
190         _serveIcon = serveIcon;
191     }
192 
193 
194 }