KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > openharmonise > rm > HarmoniseExceptionHandler


1 /*
2  * The contents of this file are subject to the
3  * Mozilla Public License Version 1.1 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at http://www.mozilla.org/MPL/
6  *
7  * Software distributed under the License is distributed on an "AS IS"
8  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied.
9  * See the License for the specific language governing rights and
10  * limitations under the License.
11  *
12  * The Initial Developer of the Original Code is Simulacra Media Ltd.
13  * Portions created by Simulacra Media Ltd are Copyright (C) Simulacra Media Ltd, 2004.
14  *
15  * All Rights Reserved.
16  *
17  * Contributor(s):
18  */

19 package org.openharmonise.rm;
20
21 import java.io.*;
22 import java.text.*;
23 import java.util.*;
24
25 import javax.servlet.http.*;
26
27 import org.openharmonise.commons.net.*;
28 import org.openharmonise.rm.config.*;
29
30 /**
31  * A class to handle exceptions thrown within Harmonise.
32  * @author Michael Bell
33  * @version $Revision: 1.1 $
34  *
35  */

36 public class HarmoniseExceptionHandler {
37     /**
38      * Email address configuration parameter name
39      */

40     static final String JavaDoc EMAIL_ADDRESS_PNAME = "ERROR_EMAIL_ADDRESS";
41     /**
42      * Email errors switch configuration parameter name
43      */

44     static final String JavaDoc EMAIL_ERRORS_PNAME = "EMAIL_ERRORS";
45     /**
46      * Redirect address configuration parameter name
47      */

48     static final String JavaDoc REDIRECT_URL_PNAME = "ERROR_REDIRECT_URL";
49     /**
50      * Redirect on error switch configuration parameter name
51      */

52     static final String JavaDoc USE_REDIRECT_PNAME = "REDIRECT_ON_ERROR";
53     /**
54      * The from address for sent emails
55      */

56     static final String JavaDoc ERRORS_FROMADDRESS = "ErrorMail@simulacramedia.com";
57
58     /**
59      * Array of address to email errors to
60      */

61     private String JavaDoc[] m_error_email_toaddresses = new String JavaDoc[1];
62     /**
63      * <code>boolean</code> switch which determines whether errors are emailed
64      */

65     private boolean m_bEmailErrors = false;
66     /**
67      * The URI context for the error being handled
68      */

69     private String JavaDoc m_reporting_URL = "Not known";
70     /**
71      * The 'from' address for emails sent by this error handler
72      */

73     private String JavaDoc m_originator_email_address = ERRORS_FROMADDRESS;
74     /**
75      * The string representation of date this exception was recorded
76      */

77     private String JavaDoc m_exception_date_string = "Not known";
78     /**
79      * Any additional information to be included in the exception report
80      */

81     private String JavaDoc m_additional_info = "None provided";
82     /**
83      * <code>boolean</code> switch which determines whether the redirect URI is used
84      */

85     private boolean m_use_redirect = false;
86     /**
87      * The redirect URI
88      */

89     private String JavaDoc m_redirect_URL = "/errors/404.htm";
90     /**
91      * The importance email header value
92      */

93     protected String JavaDoc m_sImportance = null;
94
95     /**
96      * Constructs a new exception handler with the settings taken from
97      * the <code>ConfigSettings</code> class
98      *
99      * @throws Exception if any errors occur
100      */

101     public HarmoniseExceptionHandler() throws Exception JavaDoc {
102         String JavaDoc error_email_toaddress =
103             ConfigSettings.getProperty(EMAIL_ADDRESS_PNAME);
104         m_error_email_toaddresses[0] = error_email_toaddress;
105
106         m_use_redirect =
107             ConfigSettings.getBoolProperty(
108                 USE_REDIRECT_PNAME,
109                 "false");
110
111         m_redirect_URL =
112             ConfigSettings.getProperty(
113                 REDIRECT_URL_PNAME,
114                 m_redirect_URL);
115
116         m_bEmailErrors =
117             ConfigSettings.getBoolProperty(
118                 EMAIL_ERRORS_PNAME,
119                 "false");
120
121         this.updateExceptionDate();
122     }
123
124     /**
125      * Handle the specified exception, emailing a report and/or redirecting
126      * the reponse object
127      *
128      * @param additional_info the additional information to be included in the report
129      * @param e the exception to be 'handled'
130      * @param request the servlet request
131      * @param response the servlet response
132      * @param out the <code>PrintWriter</code> to print the report to if redirecting
133      * has been switched off
134      * @throws Exception if any errors occur
135      */

136     public void handle(
137         String JavaDoc additional_info,
138         Throwable JavaDoc e,
139         HttpServletRequest request,
140         HttpServletResponse response,
141         PrintWriter out)
142         throws Exception JavaDoc {
143         m_additional_info = additional_info;
144
145         m_reporting_URL = request.getRequestURI();
146
147         String JavaDoc exception_description = describeException(request, e);
148
149         if (m_bEmailErrors) {
150             emailError(exception_description, e);
151         } // email errors
152

153         // always put a note in the log
154
//cat.fatal("** Exception:" + exception_description);
155

156         if (m_use_redirect) {
157             response.sendRedirect(m_redirect_URL);
158         } else {
159             if (out != null) {
160                 out.println("<pre>");
161                 out.println(exception_description);
162                 out.println("</pre>");
163             }
164         }
165     }
166
167     /**
168      * Emails the given exception with no importance heading value set
169      * and a standard subject heading
170      *
171      * @param exception_description a description of the exception
172      * @param e the exception
173      * @throws Exception if any errors occur
174      */

175     public void emailError(String JavaDoc exception_description, Throwable JavaDoc e)
176         throws Exception JavaDoc {
177         emailError(exception_description, e, false);
178     }
179
180     /**
181      * Emails the given exception with the specified importance heading value
182      * set and a standard subject heading
183      *
184      * @param exception_description a description of the exception
185      * @param e the exception
186      * @param bEmphasize the importance heading value
187      * @throws Exception if any errors occur
188      */

189     public void emailError(
190         String JavaDoc exception_description,
191         Throwable JavaDoc e,
192         boolean bEmphasize)
193         throws Exception JavaDoc {
194         String JavaDoc sSubject =
195             "Error for "
196                 + m_reporting_URL
197                 + " ["
198                 + m_exception_date_string
199                 + "]";
200
201         emailError(sSubject, exception_description, e, bEmphasize);
202     }
203
204     /**
205      * Emails the given exception with no importance heading value
206      * set and the specified subject heading
207      *
208      * @param sSubject the email subject
209      * @param exception_description a description of the exception
210      * @param e the exception
211      * @throws Exception if any errors occur
212      */

213     public void emailError(
214         String JavaDoc sSubject,
215         String JavaDoc exception_description,
216         Throwable JavaDoc e)
217         throws Exception JavaDoc {
218         emailError(sSubject, exception_description, e, false);
219     }
220
221     /**
222      * Emails the given exception with the specified importance heading value
223      * set and subject heading
224      *
225      * @param sSubject the email subject
226      * @param exception_description a description of the exception
227      * @param e the exception
228      * @param bEmphasize the importance heading value
229      * @throws Exception if any errors occur
230      */

231     public void emailError(
232         String JavaDoc sSubject,
233         String JavaDoc exception_description,
234         Throwable JavaDoc e,
235         boolean bEmphasize)
236         throws Exception JavaDoc {
237
238         if (bEmphasize == true) {
239             sSubject = sSubject.toUpperCase();
240         }
241
242         Email email =
243             new Email(
244                 ConfigSettings.getProperty("EMAIL_HOST"),
245                 m_error_email_toaddresses[0],
246                 m_originator_email_address,
247                 sSubject,
248                 exception_description);
249
250         if (m_sImportance != null) {
251             email.setImportance(m_sImportance);
252         }
253
254         for (int i = 0; i < m_error_email_toaddresses.length; i++) {
255             email.SetEmailAddress(m_error_email_toaddresses[i]);
256             email.send();
257         }
258
259     }
260
261     /**
262      * Sets this handler's formatted date field
263      *
264      */

265     private void updateExceptionDate() {
266         SimpleDateFormat formatter =
267             new SimpleDateFormat("EEEE yyyyy-MMMM-dd 'at' hh:mm:ss zzzz");
268
269         java.util.Date JavaDoc current_time = new java.util.Date JavaDoc();
270         m_exception_date_string = formatter.format(current_time);
271     }
272
273     /**
274      * Sets the email importance heading value
275      *
276      * @param sImportance the email importance heading value
277      */

278     public void setImportance(String JavaDoc sImportance) {
279         this.m_sImportance = sImportance;
280     }
281
282     /**
283      * Returns a string decription of the specified exception
284      *
285      * @param e the exception
286      * @return a string description of the specified exception
287      */

288     public String JavaDoc describeException(Exception JavaDoc e) {
289         StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
290         String JavaDoc EOL = "\n";
291
292         strbuf.append("[").append(m_reporting_URL).append("]").append(EOL);
293         strbuf.append(m_exception_date_string).append(EOL);
294         strbuf.append(EOL);
295
296         strbuf.append("The following error occured:").append(EOL);
297         strbuf.append(" '").append(e).append("'").append(EOL);
298         strbuf.append(EOL);
299
300         // Additional info
301
strbuf.append("Additional information:").append(EOL);
302         strbuf.append(m_additional_info).append(EOL);
303         strbuf.append(EOL);
304
305         // Stacktrace
306
strbuf.append("-- Stacktrace:").append(EOL);
307         ;
308         strbuf.append(getStackTraceAsString(e));
309
310         return (strbuf.toString());
311     }
312     
313     /**
314      * Returns a string description of the specified exception, including
315      * contextual information taken from the servlet request
316      *
317      * @param request the servlet request
318      * @param e the exception
319      * @return a string description
320      */

321     public String JavaDoc describeException(HttpServletRequest request, Throwable JavaDoc e) {
322         StringBuffer JavaDoc strbuf = new StringBuffer JavaDoc();
323         String JavaDoc EOL = "\n";
324
325         strbuf.append("[").append(m_reporting_URL).append("]").append(EOL);
326         strbuf.append(m_exception_date_string).append(EOL);
327         strbuf.append(EOL);
328
329         strbuf.append("The following error occured:").append(EOL);
330         strbuf.append(" '").append(e).append("'").append(EOL);
331         strbuf.append(EOL);
332
333         // Additional info
334
strbuf.append("Additional information:").append(EOL);
335         strbuf.append(m_additional_info).append(EOL);
336         strbuf.append(EOL);
337
338         // Reguest info
339
strbuf.append("-- Request:\n");
340         strbuf.append("URI :").append(request.getRequestURI()).append(EOL);
341         strbuf.append("Query :?").append(request.getQueryString()).append(EOL);
342         strbuf.append("Path info :").append(request.getPathInfo()).append(EOL);
343         strbuf.append("User IP :").append(request.getRemoteAddr()).append(EOL);
344         strbuf.append("Remote Host :").append(request.getRemoteHost()).append(
345             EOL);
346         strbuf.append("Remote User :").append(request.getRemoteUser()).append(
347             EOL);
348         strbuf.append("Request method :").append(request.getMethod()).append(
349             EOL);
350         strbuf.append("Servlet Path :").append(
351             request.getServletPath()).append(
352             EOL);
353
354         strbuf.append(EOL);
355
356         // Header info
357
strbuf.append("-- Header Info:").append(EOL);
358
359         Enumeration header_names = request.getHeaderNames();
360
361         while (header_names.hasMoreElements()) {
362             String JavaDoc name = (String JavaDoc) header_names.nextElement();
363             strbuf.append(" ");
364             strbuf.append(name);
365             strbuf.append(": ");
366             strbuf.append(request.getHeader(name));
367             strbuf.append(EOL);
368         }
369
370         strbuf.append(EOL);
371
372         // Cookies
373
Cookie[] cookies = request.getCookies();
374
375         if (cookies != null) {
376             strbuf.append("-- Cookies:").append(EOL);
377
378             for (int i = 0; i < cookies.length; i++) {
379                 Cookie this_cookie = cookies[i];
380                 strbuf.append(" ");
381                 strbuf.append(this_cookie.getName());
382                 strbuf.append(": ");
383                 strbuf.append(this_cookie.getValue());
384                 strbuf.append(EOL);
385             }
386         }
387
388         strbuf.append(EOL);
389
390         // Stacktrace
391
strbuf.append("-- Stacktrace:").append(EOL);
392         ;
393         strbuf.append(getStackTraceAsString(e));
394
395         return (strbuf.toString());
396     }
397
398     /**
399      * Returns a <code>String</code> representation of the given <code>Exception</code>
400      *
401      * @param e the exception
402      * @return a <code>String</code> representation of the given <code>Exception</code>
403      */

404     private static String JavaDoc getStackTraceAsString(Throwable JavaDoc e) {
405         StringWriter sw = new StringWriter();
406         PrintWriter pw = new PrintWriter(sw);
407         e.printStackTrace(pw);
408         pw.close();
409
410         return sw.toString();
411     }
412 }
Popular Tags