View Javadoc

1   /* ====================================================================
2    * The Apache Software License, Version 1.1
3    *
4    * Copyright (c) 2002-2003 The Apache Software Foundation.  All rights
5    * reserved.
6    *
7    * Redistribution and use in source and binary forms, with or without
8    * modification, are permitted provided that the following conditions
9    * are met:
10   *
11   * 1. Redistributions of source code must retain the above copyright
12   *    notice, this list of conditions and the following disclaimer.
13   *
14   * 2. Redistributions in binary form must reproduce the above copyright
15   *    notice, this list of conditions and the following disclaimer in
16   *    the documentation and/or other materials provided with the
17   *    distribution.
18   *
19   * 3. The end-user documentation included with the redistribution, if
20   *    any, must include the following acknowledgement:
21   *       "This product includes software developed by the
22   *        Apache Software Foundation (http://www.apache.org/)."
23   *    Alternately, this acknowledgement may appear in the software itself,
24   *    if and wherever such third-party acknowledgements normally appear.
25   *
26   * 4. The names "The Jakarta Project", "Commons", and "Apache Software
27   *    Foundation" must not be used to endorse or promote products derived
28   *    from this software without prior written permission. For written
29   *    permission, please contact apache@apache.org.
30   *
31   * 5. Products derived from this software may not be called "Apache"
32   *    nor may "Apache" appear in their names without prior written
33   *    permission of the Apache Software Foundation.
34   *
35   * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36   * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37   * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38   * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39   * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40   * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41   * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42   * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43   * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45   * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46   * SUCH DAMAGE.
47   * ====================================================================
48   *
49   * This software consists of voluntary contributions made by many
50   * individuals on behalf of the Apache Software Foundation.  For more
51   * information on the Apache Software Foundation, please see
52   * <http://www.apache.org/>.
53   */
54  package org.jdiagnose.exception;
55  
56  import java.io.PrintStream;
57  import java.io.PrintWriter;
58  import java.io.Serializable;
59  import java.io.StringWriter;
60  import java.util.ArrayList;
61  import java.util.Arrays;
62  import java.util.Collections;
63  import java.util.Iterator;
64  import java.util.List;
65  
66  /***
67   * <p>A shared implementation of the nestable exception functionality.</p>
68   * <p>
69   * The code is shared between 
70   * {@link org.jdiagnose.exception.NestableError NestableError},
71   * {@link org.jdiagnose.exception.NestableException NestableException} and
72   * {@link org.jdiagnose.exception.NestableRuntimeException NestableRuntimeException}.
73   * </p>
74   * 
75   * @author <a href="mailto:Rafal.Krzewski@e-point.pl">Rafal Krzewski</a>
76   * @author <a href="mailto:dlr@collab.net">Daniel Rall</a>
77   * @author <a href="mailto:knielsen@apache.org">Kasper Nielsen</a>
78   * @author <a href="mailto:steven@caswell.name">Steven Caswell</a>
79   * @author Sean C. Sullivan
80   * @author Stephen Colebourne
81   * @since 1.0
82   * @version $Id: NestableDelegate.java,v 1.2 2005/03/02 17:07:09 dkfn Exp $
83   */
84  public class NestableDelegate implements Serializable {
85  
86      /***
87       * Constructor error message.
88       */
89      private transient static final String MUST_BE_THROWABLE =
90          "The Nestable implementation passed to the NestableDelegate(Nestable) "
91              + "constructor must extend java.lang.Throwable";
92  
93      /***
94       * Holds the reference to the exception or error that we're
95       * wrapping (which must be a {@link
96       * org.jdiagnose.exception.Nestable} implementation).
97       */
98      private Throwable nestable = null;
99      
100     /***
101      * Whether to print the stack trace top-down.
102      * This public flag may be set by calling code, typically in initialisation.
103      * @since 2.0
104      */
105     public static boolean topDown = true;
106     
107     /***
108      * Whether to trim the repeated stack trace.
109      * This public flag may be set by calling code, typically in initialisation.
110      * @since 2.0
111      */
112     public static boolean trimStackFrames = true;
113 
114     /***
115      * Constructs a new <code>NestableDelegate</code> instance to manage the
116      * specified <code>Nestable</code>.
117      *
118      * @param nestable the Nestable implementation (<i>must</i> extend
119      * {@link java.lang.Throwable})
120      * @since 2.0
121      */
122     public NestableDelegate(Nestable nestable) {
123         if (nestable instanceof Throwable) {
124             this.nestable = (Throwable) nestable;
125         } else {
126             throw new IllegalArgumentException(MUST_BE_THROWABLE);
127         }
128     }
129 
130     /***
131      * Returns the error message of the <code>Throwable</code> in the chain
132      * of <code>Throwable</code>s at the specified index, numbered from 0.
133      *
134      * @param index the index of the <code>Throwable</code> in the chain of
135      * <code>Throwable</code>s
136      * @return the error message, or null if the <code>Throwable</code> at the
137      * specified index in the chain does not contain a message
138      * @throws IndexOutOfBoundsException if the <code>index</code> argument is
139      * negative or not less than the count of <code>Throwable</code>s in the
140      * chain
141      * @since 2.0
142      */
143     public String getMessage(int index) {
144         Throwable t = this.getThrowable(index);
145         if (Nestable.class.isInstance(t)) {
146             return ((Nestable) t).getMessage(0);
147         } else {
148             return t.getMessage();
149         }
150     }
151 
152     /***
153      * Returns the full message contained by the <code>Nestable</code>
154      * and any nested <code>Throwable</code>s.
155      *
156      * @param baseMsg the base message to use when creating the full
157      * message. Should be generally be called via
158      * <code>nestableHelper.getMessage(super.getMessage())</code>,
159      * where <code>super</code> is an instance of {@link
160      * java.lang.Throwable}.
161      * @return The concatenated message for this and all nested
162      * <code>Throwable</code>s
163      * @since 2.0
164      */
165     public String getMessage(String baseMsg) {
166         StringBuffer msg = new StringBuffer();
167         if (baseMsg != null) {
168             msg.append(baseMsg);
169         }
170 
171         Throwable nestedCause = ExceptionUtils.getCause(this.nestable);
172         if (nestedCause != null) {
173             String causeMsg = nestedCause.getMessage();
174             if (causeMsg != null) {
175                 if (baseMsg != null) {
176                     msg.append(": ");
177                 }
178                 msg.append(causeMsg);
179             }
180 
181         }
182         return (msg.length() > 0 ? msg.toString() : null);
183     }
184 
185     /***
186      * Returns the error message of this and any nested <code>Throwable</code>s
187      * in an array of Strings, one element for each message. Any
188      * <code>Throwable</code> not containing a message is represented in the
189      * array by a null. This has the effect of cause the length of the returned
190      * array to be equal to the result of the {@link #getThrowableCount()}
191      * operation.
192      *
193      * @return the error messages
194      * @since 2.0
195      */
196     public String[] getMessages() {
197         Throwable[] throwables = this.getThrowables();
198         String[] msgs = new String[throwables.length];
199         for (int i = 0; i < throwables.length; i++) {
200             msgs[i] =
201                 (Nestable.class.isInstance(throwables[i])
202                     ? ((Nestable) throwables[i]).getMessage(0)
203                     : throwables[i].getMessage());
204         }
205         return msgs;
206     }
207 
208     /***
209      * Returns the <code>Throwable</code> in the chain of
210      * <code>Throwable</code>s at the specified index, numbered from 0.
211      *
212      * @param index the index, numbered from 0, of the <code>Throwable</code> in
213      * the chain of <code>Throwable</code>s
214      * @return the <code>Throwable</code>
215      * @throws IndexOutOfBoundsException if the <code>index</code> argument is
216      * negative or not less than the count of <code>Throwable</code>s in the
217      * chain
218      * @since 2.0
219      */
220     public Throwable getThrowable(int index) {
221         if (index == 0) {
222             return this.nestable;
223         }
224         Throwable[] throwables = this.getThrowables();
225         return throwables[index];
226     }
227 
228     /***
229      * Returns the number of <code>Throwable</code>s contained in the
230      * <code>Nestable</code> contained by this remoteResult.
231      *
232      * @return the throwable count
233      * @since 2.0
234      */
235     public int getThrowableCount() {
236         return ExceptionUtils.getThrowableCount(this.nestable);
237     }
238 
239     /***
240      * Returns this remoteResult's <code>Nestable</code> and any nested
241      * <code>Throwable</code>s in an array of <code>Throwable</code>s, one
242      * element for each <code>Throwable</code>.
243      *
244      * @return the <code>Throwable</code>s
245      * @since 2.0
246      */
247     public Throwable[] getThrowables() {
248         return ExceptionUtils.getThrowables(this.nestable);
249     }
250 
251     /***
252      * Returns the index, numbered from 0, of the first <code>Throwable</code>
253      * that matches the specified type in the chain of <code>Throwable</code>s
254      * held in this remoteResult's <code>Nestable</code> with an index greater than
255      * or equal to the specified index, or -1 if the type is not found.
256      *
257      * @param type <code>Class</code> to be found
258      * @param fromIndex the index, numbered from 0, of the starting position in
259      * the chain to be searched
260      * @return index of the first occurrence of the type in the chain, or -1 if
261      * the type is not found
262      * @throws IndexOutOfBoundsException if the <code>fromIndex</code> argument
263      * is negative or not less than the count of <code>Throwable</code>s in the
264      * chain
265      * @since 2.0
266      */
267     public int indexOfThrowable(Class type, int fromIndex) {
268         if (fromIndex < 0) {
269             throw new IndexOutOfBoundsException("The start index was out of bounds: " + fromIndex);
270         }
271         Throwable[] throwables = ExceptionUtils.getThrowables(this.nestable);
272         if (fromIndex >= throwables.length) {
273             throw new IndexOutOfBoundsException("The start index was out of bounds: "
274                 + fromIndex + " >= " + throwables.length);
275         }
276         for (int i = fromIndex; i < throwables.length; i++) {
277             if (throwables[i].getClass().equals(type)) {
278                 return i;
279             }
280         }
281         return -1;
282     }
283 
284     /***
285      * Prints the stack trace of this exception the the standar error
286      * stream.
287      */
288     public void printStackTrace() {
289         printStackTrace(System.err);
290     }
291 
292     /***
293      * Prints the stack trace of this exception to the specified
294      * stream.
295      *
296      * @param out <code>PrintStream</code> to use for output.
297      * @see #printStackTrace(PrintWriter)
298      */
299     public void printStackTrace(PrintStream out) {
300         synchronized (out) {
301             PrintWriter pw = new PrintWriter(out, false);
302             printStackTrace(pw);
303             // Flush the PrintWriter before it's GC'ed.
304             pw.flush();
305         }
306     }
307 
308     /***
309      * Prints the stack trace of this exception to the specified
310      * writer. If the Throwable class has a <code>getCause</code>
311      * method (i.e. running on jre1.4 or higher), this method just 
312      * uses Throwable's printStackTrace() method. Otherwise, generates
313      * the stack-trace, by taking into account the 'topDown' and 
314      * 'trimStackFrames' parameters. The topDown and trimStackFrames 
315      * are set to 'true' by default (produces jre1.4-like stack trace).
316      *
317      * @param out <code>PrintWriter</code> to use for output.
318      */
319     public void printStackTrace(PrintWriter out) {
320         Throwable throwable = this.nestable;
321         // if running on jre1.4 or higher, use default printStackTrace
322         if (ExceptionUtils.isThrowableNested()) {
323             if (throwable instanceof Nestable) {
324                 ((Nestable)throwable).printPartialStackTrace(out);
325             } else {
326                 throwable.printStackTrace(out);
327             }
328             return;
329         }
330 
331         // generating the nested stack trace
332         List stacks = new ArrayList();
333         while (throwable != null) {
334             String[] st = getStackFrames(throwable);
335             stacks.add(st);
336             throwable = ExceptionUtils.getCause(throwable);
337         }
338 
339         // If NOT topDown, reverse the stack
340         String separatorLine = "Caused by: ";
341         if (!topDown) {
342             separatorLine = "Rethrown as: ";
343             Collections.reverse(stacks);
344         }
345 
346         // Remove the repeated lines in the stack
347         if (trimStackFrames) {
348           trimStackFrames(stacks);
349         }
350 
351         synchronized (out) {
352             for (Iterator iter=stacks.iterator(); iter.hasNext();) {
353                 String[] st = (String[]) iter.next();
354                 for (int i=0, len=st.length; i < len; i++) {
355                     out.println(st[i]);
356                 }
357                 if (iter.hasNext()) {
358                     out.print(separatorLine);
359                 }
360             }
361         }
362     }
363 
364     /***
365      * Captures the stack trace associated with the specified
366      * <code>Throwable</code> object, decomposing it into a list of
367      * stack frames.
368      *
369      * @param t The <code>Throwable</code>.
370      * @return  An array of strings describing each stack frame.
371      * @since 2.0
372      */
373     protected String[] getStackFrames(Throwable t) {
374         StringWriter sw = new StringWriter();
375         PrintWriter pw = new PrintWriter(sw, true);
376 
377         // Avoid infinite loop between decompose() and printStackTrace().
378         if (t instanceof Nestable) {
379             ((Nestable) t).printPartialStackTrace(pw);
380         } else {
381             t.printStackTrace(pw);
382         }
383         return ExceptionUtils.getStackFrames(sw.getBuffer().toString());
384     }
385     
386     /***
387      * Trims the stack frames. The first set is left untouched. The rest
388      * of the frames are truncated from the bottom by comparing with
389      * one just on top.
390      *
391      * @param stacks The list containing String[] elements
392      * @since 2.0
393      */
394     protected void trimStackFrames(List stacks) {
395          for (int size=stacks.size(), i=size-1; i > 0; i--) {
396              String[] curr = (String[]) stacks.get(i);
397              String[] next = (String[]) stacks.get(i-1); 
398              
399              List currList = new ArrayList(Arrays.asList(curr));
400              List nextList = new ArrayList(Arrays.asList(next));
401              ExceptionUtils.removeCommonFrames(currList, nextList);
402 
403              int trimmed = curr.length - currList.size();
404              if (trimmed > 0) {
405                  currList.add("\t... "+trimmed+" more");
406                  stacks.set(
407                      i, 
408                      currList.toArray(new String[currList.size()])
409                  );
410              }
411          }
412      }
413 }