View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.server.handler;
20  
21  import java.io.IOException;
22  import java.io.PrintWriter;
23  import java.io.StringWriter;
24  import java.io.Writer;
25  import java.nio.ByteBuffer;
26  
27  import javax.servlet.ServletException;
28  import javax.servlet.http.HttpServletRequest;
29  import javax.servlet.http.HttpServletResponse;
30  
31  import org.eclipse.jetty.http.HttpFields;
32  import org.eclipse.jetty.http.HttpHeader;
33  import org.eclipse.jetty.http.HttpMethod;
34  import org.eclipse.jetty.http.HttpStatus;
35  import org.eclipse.jetty.http.MimeTypes;
36  import org.eclipse.jetty.server.Dispatcher;
37  import org.eclipse.jetty.server.Request;
38  import org.eclipse.jetty.server.Response;
39  import org.eclipse.jetty.server.Server;
40  import org.eclipse.jetty.util.BufferUtil;
41  import org.eclipse.jetty.util.ByteArrayISO8859Writer;
42  import org.eclipse.jetty.util.StringUtil;
43  import org.eclipse.jetty.util.log.Log;
44  import org.eclipse.jetty.util.log.Logger;
45  
46  /* ------------------------------------------------------------ */
47  /** Handler for Error pages
48   * An ErrorHandler is registered with {@link ContextHandler#setErrorHandler(ErrorHandler)} or
49   * {@link org.eclipse.jetty.server.Server#addBean(Object)}.
50   * It is called by the HttpResponse.sendError method to write a error page via {@link #handle(String, Request, HttpServletRequest, HttpServletResponse)}
51   * or via {@link #badMessageError(int, String, HttpFields)} for bad requests for which a dispatch cannot be done.
52   *
53   */
54  public class ErrorHandler extends AbstractHandler
55  {    
56      private static final Logger LOG = Log.getLogger(ErrorHandler.class);
57      public final static String ERROR_PAGE="org.eclipse.jetty.server.error_page";
58      
59      boolean _showStacks=true;
60      boolean _showMessageInTitle=true;
61      String _cacheControl="must-revalidate,no-cache,no-store";
62  
63      /* ------------------------------------------------------------ */
64      /*
65       * @see org.eclipse.jetty.server.server.Handler#handle(javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse, int)
66       */
67      @Override
68      public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException
69      {
70          String method = request.getMethod();
71          if (!HttpMethod.GET.is(method) && !HttpMethod.POST.is(method) && !HttpMethod.HEAD.is(method))
72          {
73              baseRequest.setHandled(true);
74              return;
75          }
76          
77          if (this instanceof ErrorPageMapper)
78          {
79              String error_page=((ErrorPageMapper)this).getErrorPage(request);
80              if (error_page!=null && request.getServletContext()!=null)
81              {
82                  String old_error_page=(String)request.getAttribute(ERROR_PAGE);
83                  if (old_error_page==null || !old_error_page.equals(error_page))
84                  {
85                      request.setAttribute(ERROR_PAGE, error_page);
86  
87                      Dispatcher dispatcher = (Dispatcher) request.getServletContext().getRequestDispatcher(error_page);
88                      try
89                      {
90                          if(dispatcher!=null)
91                          {
92                              dispatcher.error(request, response);
93                              return;
94                          }
95                          LOG.warn("No error page "+error_page);
96                      }
97                      catch (ServletException e)
98                      {
99                          LOG.warn(Log.EXCEPTION, e);
100                         return;
101                     }
102                 }
103             }
104         }
105         
106         baseRequest.setHandled(true);
107         response.setContentType(MimeTypes.Type.TEXT_HTML_8859_1.asString());    
108         if (_cacheControl!=null)
109             response.setHeader(HttpHeader.CACHE_CONTROL.asString(), _cacheControl);
110         ByteArrayISO8859Writer writer= new ByteArrayISO8859Writer(4096);
111         String reason=(response instanceof Response)?((Response)response).getReason():null;
112         handleErrorPage(request, writer, response.getStatus(), reason);
113         writer.flush();
114         response.setContentLength(writer.size());
115         writer.writeTo(response.getOutputStream());
116         writer.destroy();
117     }
118 
119     /* ------------------------------------------------------------ */
120     protected void handleErrorPage(HttpServletRequest request, Writer writer, int code, String message)
121         throws IOException
122     {
123         writeErrorPage(request, writer, code, message, _showStacks);
124     }
125 
126     /* ------------------------------------------------------------ */
127     protected void writeErrorPage(HttpServletRequest request, Writer writer, int code, String message, boolean showStacks)
128         throws IOException
129     {
130         if (message == null)
131             message=HttpStatus.getMessage(code);
132 
133         writer.write("<html>\n<head>\n");
134         writeErrorPageHead(request,writer,code,message);
135         writer.write("</head>\n<body>");
136         writeErrorPageBody(request,writer,code,message,showStacks);
137         writer.write("\n</body>\n</html>\n");
138     }
139 
140     /* ------------------------------------------------------------ */
141     protected void writeErrorPageHead(HttpServletRequest request, Writer writer, int code, String message)
142         throws IOException
143         {
144         writer.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"/>\n");
145         writer.write("<title>Error ");
146         writer.write(Integer.toString(code));
147 
148         if (_showMessageInTitle)
149         {
150             writer.write(' ');
151             write(writer,message);
152         }
153         writer.write("</title>\n");
154     }
155 
156     /* ------------------------------------------------------------ */
157     protected void writeErrorPageBody(HttpServletRequest request, Writer writer, int code, String message, boolean showStacks)
158         throws IOException
159     {
160         String uri= request.getRequestURI();
161 
162         writeErrorPageMessage(request,writer,code,message,uri);
163         if (showStacks)
164             writeErrorPageStacks(request,writer);
165         writer.write("<hr><i><small>Powered by Jetty://</small></i><hr/>\n");
166     }
167 
168     /* ------------------------------------------------------------ */
169     protected void writeErrorPageMessage(HttpServletRequest request, Writer writer, int code, String message,String uri)
170     throws IOException
171     {
172         writer.write("<h2>HTTP ERROR ");
173         writer.write(Integer.toString(code));
174         writer.write("</h2>\n<p>Problem accessing ");
175         write(writer,uri);
176         writer.write(". Reason:\n<pre>    ");
177         write(writer,message);
178         writer.write("</pre></p>");
179     }
180 
181     /* ------------------------------------------------------------ */
182     protected void writeErrorPageStacks(HttpServletRequest request, Writer writer)
183         throws IOException
184     {
185         Throwable th = (Throwable)request.getAttribute("javax.servlet.error.exception");
186         while(th!=null)
187         {
188             writer.write("<h3>Caused by:</h3><pre>");
189             StringWriter sw = new StringWriter();
190             PrintWriter pw = new PrintWriter(sw);
191             th.printStackTrace(pw);
192             pw.flush();
193             write(writer,sw.getBuffer().toString());
194             writer.write("</pre>\n");
195 
196             th =th.getCause();
197         }
198     }
199 
200     /* ------------------------------------------------------------ */
201     /** Bad Message Error body
202      * <p>Generate a error response body to be sent for a bad message.
203      * In this case there is something wrong with the request, so either
204      * a request cannot be built, or it is not safe to build a request.
205      * This method allows for a simple error page body to be returned 
206      * and some response headers to be set.
207      * @param status The error code that will be sent
208      * @param reason The reason for the error code (may be null)
209      * @param fields The header fields that will be sent with the response.
210      * @return The content as a ByteBuffer, or null for no body.
211      */
212     public ByteBuffer badMessageError(int status, String reason, HttpFields fields)
213     {
214         if (reason==null)
215             reason=HttpStatus.getMessage(status);
216         fields.put(HttpHeader.CONTENT_TYPE,MimeTypes.Type.TEXT_HTML_8859_1.asString());
217         return BufferUtil.toBuffer("<h1>Bad Message " + status + "</h1><pre>reason: " + reason + "</pre>");
218     }    
219     
220     /* ------------------------------------------------------------ */
221     /** Get the cacheControl.
222      * @return the cacheControl header to set on error responses.
223      */
224     public String getCacheControl()
225     {
226         return _cacheControl;
227     }
228 
229     /* ------------------------------------------------------------ */
230     /** Set the cacheControl.
231      * @param cacheControl the cacheControl header to set on error responses.
232      */
233     public void setCacheControl(String cacheControl)
234     {
235         _cacheControl = cacheControl;
236     }
237 
238     /* ------------------------------------------------------------ */
239     /**
240      * @return True if stack traces are shown in the error pages
241      */
242     public boolean isShowStacks()
243     {
244         return _showStacks;
245     }
246 
247     /* ------------------------------------------------------------ */
248     /**
249      * @param showStacks True if stack traces are shown in the error pages
250      */
251     public void setShowStacks(boolean showStacks)
252     {
253         _showStacks = showStacks;
254     }
255 
256     /* ------------------------------------------------------------ */
257     /**
258      * @param showMessageInTitle if true, the error message appears in page title
259      */
260     public void setShowMessageInTitle(boolean showMessageInTitle)
261     {
262         _showMessageInTitle = showMessageInTitle;
263     }
264 
265 
266     /* ------------------------------------------------------------ */
267     public boolean getShowMessageInTitle()
268     {
269         return _showMessageInTitle;
270     }
271 
272     /* ------------------------------------------------------------ */
273     protected void write(Writer writer,String string)
274         throws IOException
275     {
276         if (string==null)
277             return;
278 
279         writer.write(StringUtil.sanitizeXmlString(string));
280     }
281 
282     /* ------------------------------------------------------------ */
283     public interface ErrorPageMapper
284     {
285         String getErrorPage(HttpServletRequest request);
286     }
287 
288     /* ------------------------------------------------------------ */
289     public static ErrorHandler getErrorHandler(Server server, ContextHandler context)
290     {
291         ErrorHandler error_handler=null;
292         if (context!=null)
293             error_handler=context.getErrorHandler();
294         if (error_handler==null && server!=null)
295             error_handler = server.getBean(ErrorHandler.class);
296         return error_handler;
297     }
298 }