KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > commons > lang > exception > ExceptionUtils


1 /*
2  * Copyright 2002-2005 The Apache Software Foundation.
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  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */

16 package org.apache.commons.lang.exception;
17
18 import java.io.PrintStream JavaDoc;
19 import java.io.PrintWriter JavaDoc;
20 import java.io.StringWriter JavaDoc;
21 import java.lang.reflect.Field JavaDoc;
22 import java.lang.reflect.InvocationTargetException JavaDoc;
23 import java.lang.reflect.Method JavaDoc;
24 import java.sql.SQLException JavaDoc;
25 import java.util.ArrayList JavaDoc;
26 import java.util.Arrays JavaDoc;
27 import java.util.LinkedList JavaDoc;
28 import java.util.List JavaDoc;
29 import java.util.StringTokenizer JavaDoc;
30
31 import org.apache.commons.lang.ArrayUtils;
32 import org.apache.commons.lang.StringUtils;
33 import org.apache.commons.lang.SystemUtils;
34
35 /**
36  * <p>Provides utilities for manipulating and examining
37  * <code>Throwable</code> objects.</p>
38  *
39  * @author <a HREF="mailto:dlr@finemaltcoding.com">Daniel Rall</a>
40  * @author Dmitri Plotnikov
41  * @author Stephen Colebourne
42  * @author <a HREF="mailto:ggregory@seagullsw.com">Gary Gregory</a>
43  * @author Pete Gieser
44  * @since 1.0
45  * @version $Id: ExceptionUtils.java 161243 2005-04-14 04:30:28Z ggregory $
46  */

47 public class ExceptionUtils {
48     
49     /**
50      * <p>Used when printing stack frames to denote the start of a
51      * wrapped exception.</p>
52      *
53      * <p>Package private for accessibility by test suite.</p>
54      */

55     static final String JavaDoc WRAPPED_MARKER = " [wrapped] ";
56
57     /**
58      * <p>The names of methods commonly used to access a wrapped exception.</p>
59      */

60     private static String JavaDoc[] CAUSE_METHOD_NAMES = {
61         "getCause",
62         "getNextException",
63         "getTargetException",
64         "getException",
65         "getSourceException",
66         "getRootCause",
67         "getCausedByException",
68         "getNested",
69         "getLinkedException",
70         "getNestedException",
71         "getLinkedCause",
72         "getThrowable",
73     };
74
75     /**
76      * <p>The Method object for JDK1.4 getCause.</p>
77      */

78     private static final Method JavaDoc THROWABLE_CAUSE_METHOD;
79     static {
80         Method JavaDoc getCauseMethod;
81         try {
82             getCauseMethod = Throwable JavaDoc.class.getMethod("getCause", null);
83         } catch (Exception JavaDoc e) {
84             getCauseMethod = null;
85         }
86         THROWABLE_CAUSE_METHOD = getCauseMethod;
87     }
88     
89     /**
90      * <p>Public constructor allows an instance of <code>ExceptionUtils</code>
91      * to be created, although that is not normally necessary.</p>
92      */

93     public ExceptionUtils() {
94     }
95
96     //-----------------------------------------------------------------------
97
/**
98      * <p>Adds to the list of method names used in the search for <code>Throwable</code>
99      * objects.</p>
100      *
101      * @param methodName the methodName to add to the list, <code>null</code>
102      * and empty strings are ignored
103      * @since 2.0
104      */

105     public static void addCauseMethodName(String JavaDoc methodName) {
106         if (StringUtils.isNotEmpty(methodName) && !isCauseMethodName(methodName)) {
107             List JavaDoc list = getCauseMethodNameList();
108             if (list.add(methodName)) {
109                 CAUSE_METHOD_NAMES = toArray(list);
110             }
111         }
112     }
113
114     /**
115      * <p>Removes from the list of method names used in the search for <code>Throwable</code>
116      * objects.</p>
117      *
118      * @param methodName the methodName to remove from the list, <code>null</code>
119      * and empty strings are ignored
120      * @since 2.1
121      */

122     public static void removeCauseMethodName(String JavaDoc methodName) {
123         if (StringUtils.isNotEmpty(methodName)) {
124             List JavaDoc list = getCauseMethodNameList();
125             if (list.remove(methodName)) {
126                 CAUSE_METHOD_NAMES = toArray(list);
127             }
128         }
129     }
130
131     /**
132      * Returns the given list as a <code>String[]</code>.
133      * @param list a list to transform.
134      * @return the given list as a <code>String[]</code>.
135      */

136     private static String JavaDoc[] toArray(List JavaDoc list) {
137         return (String JavaDoc[]) list.toArray(new String JavaDoc[list.size()]);
138     }
139
140     /**
141      * Returns {@link #CAUSE_METHOD_NAMES} as a List.
142      * @return {@link #CAUSE_METHOD_NAMES} as a List.
143      */

144     private static ArrayList JavaDoc getCauseMethodNameList() {
145         return new ArrayList JavaDoc(Arrays.asList(CAUSE_METHOD_NAMES));
146     }
147
148     /**
149      * <p>Tests if the list of method names used in the search for <code>Throwable</code>
150      * objects include the given name.</p>
151      *
152      * @param methodName the methodName to search in the list.
153      * @return if the list of method names used in the search for <code>Throwable</code>
154      * objects include the given name.
155      * @since 2.1
156      */

157     public static boolean isCauseMethodName(String JavaDoc methodName) {
158         return ArrayUtils.indexOf(CAUSE_METHOD_NAMES, methodName) >= 0;
159     }
160
161     /**
162      * <p>Introspects the <code>Throwable</code> to obtain the cause.</p>
163      *
164      * <p>The method searches for methods with specific names that return a
165      * <code>Throwable</code> object. This will pick up most wrapping exceptions,
166      * including those from JDK 1.4, and
167      * {@link org.apache.commons.lang.exception.NestableException NestableException}.
168      * The method names can be added to using {@link #addCauseMethodName(String)}.</p>
169      *
170      * <p>The default list searched for are:</p>
171      * <ul>
172      * <li><code>getCause()</code></li>
173      * <li><code>getNextException()</code></li>
174      * <li><code>getTargetException()</code></li>
175      * <li><code>getException()</code></li>
176      * <li><code>getSourceException()</code></li>
177      * <li><code>getRootCause()</code></li>
178      * <li><code>getCausedByException()</code></li>
179      * <li><code>getNested()</code></li>
180      * </ul>
181      *
182      * <p>In the absence of any such method, the object is inspected for a
183      * <code>detail</code> field assignable to a <code>Throwable</code>.</p>
184      *
185      * <p>If none of the above is found, returns <code>null</code>.</p>
186      *
187      * @param throwable the throwable to introspect for a cause, may be null
188      * @return the cause of the <code>Throwable</code>,
189      * <code>null</code> if none found or null throwable input
190      * @since 1.0
191      */

192     public static Throwable JavaDoc getCause(Throwable JavaDoc throwable) {
193         return getCause(throwable, CAUSE_METHOD_NAMES);
194     }
195
196     /**
197      * <p>Introspects the <code>Throwable</code> to obtain the cause.</p>
198      *
199      * <ol>
200      * <li>Try known exception types.</li>
201      * <li>Try the supplied array of method names.</li>
202      * <li>Try the field 'detail'.</li>
203      * </ol>
204      *
205      * <p>A <code>null</code> set of method names means use the default set.
206      * A <code>null</code> in the set of method names will be ignored.</p>
207      *
208      * @param throwable the throwable to introspect for a cause, may be null
209      * @param methodNames the method names, null treated as default set
210      * @return the cause of the <code>Throwable</code>,
211      * <code>null</code> if none found or null throwable input
212      * @since 1.0
213      */

214     public static Throwable JavaDoc getCause(Throwable JavaDoc throwable, String JavaDoc[] methodNames) {
215         if (throwable == null) {
216             return null;
217         }
218         Throwable JavaDoc cause = getCauseUsingWellKnownTypes(throwable);
219         if (cause == null) {
220             if (methodNames == null) {
221                 methodNames = CAUSE_METHOD_NAMES;
222             }
223             for (int i = 0; i < methodNames.length; i++) {
224                 String JavaDoc methodName = methodNames[i];
225                 if (methodName != null) {
226                     cause = getCauseUsingMethodName(throwable, methodName);
227                     if (cause != null) {
228                         break;
229                     }
230                 }
231             }
232
233             if (cause == null) {
234                 cause = getCauseUsingFieldName(throwable, "detail");
235             }
236         }
237         return cause;
238     }
239
240     /**
241      * <p>Introspects the <code>Throwable</code> to obtain the root cause.</p>
242      *
243      * <p>This method walks through the exception chain to the last element,
244      * "root" of the tree, using {@link #getCause(Throwable)}, and
245      * returns that exception.</p>
246      *
247      * @param throwable the throwable to get the root cause for, may be null
248      * @return the root cause of the <code>Throwable</code>,
249      * <code>null</code> if none found or null throwable input
250      */

251     public static Throwable JavaDoc getRootCause(Throwable JavaDoc throwable) {
252         Throwable JavaDoc cause = getCause(throwable);
253         if (cause != null) {
254             throwable = cause;
255             while ((throwable = getCause(throwable)) != null) {
256                 cause = throwable;
257             }
258         }
259         return cause;
260     }
261
262     /**
263      * <p>Finds a <code>Throwable</code> for known types.</p>
264      *
265      * <p>Uses <code>instanceof</code> checks to examine the exception,
266      * looking for well known types which could contain chained or
267      * wrapped exceptions.</p>
268      *
269      * @param throwable the exception to examine
270      * @return the wrapped exception, or <code>null</code> if not found
271      */

272     private static Throwable JavaDoc getCauseUsingWellKnownTypes(Throwable JavaDoc throwable) {
273         if (throwable instanceof Nestable) {
274             return ((Nestable) throwable).getCause();
275         } else if (throwable instanceof SQLException JavaDoc) {
276             return ((SQLException JavaDoc) throwable).getNextException();
277         } else if (throwable instanceof InvocationTargetException JavaDoc) {
278             return ((InvocationTargetException JavaDoc) throwable).getTargetException();
279         } else {
280             return null;
281         }
282     }
283
284     /**
285      * <p>Finds a <code>Throwable</code> by method name.</p>
286      *
287      * @param throwable the exception to examine
288      * @param methodName the name of the method to find and invoke
289      * @return the wrapped exception, or <code>null</code> if not found
290      */

291     private static Throwable JavaDoc getCauseUsingMethodName(Throwable JavaDoc throwable, String JavaDoc methodName) {
292         Method JavaDoc method = null;
293         try {
294             method = throwable.getClass().getMethod(methodName, null);
295         } catch (NoSuchMethodException JavaDoc ignored) {
296         } catch (SecurityException JavaDoc ignored) {
297         }
298
299         if (method != null && Throwable JavaDoc.class.isAssignableFrom(method.getReturnType())) {
300             try {
301                 return (Throwable JavaDoc) method.invoke(throwable, ArrayUtils.EMPTY_OBJECT_ARRAY);
302             } catch (IllegalAccessException JavaDoc ignored) {
303             } catch (IllegalArgumentException JavaDoc ignored) {
304             } catch (InvocationTargetException JavaDoc ignored) {
305             }
306         }
307         return null;
308     }
309
310     /**
311      * <p>Finds a <code>Throwable</code> by field name.</p>
312      *
313      * @param throwable the exception to examine
314      * @param fieldName the name of the attribute to examine
315      * @return the wrapped exception, or <code>null</code> if not found
316      */

317     private static Throwable JavaDoc getCauseUsingFieldName(Throwable JavaDoc throwable, String JavaDoc fieldName) {
318         Field JavaDoc field = null;
319         try {
320             field = throwable.getClass().getField(fieldName);
321         } catch (NoSuchFieldException JavaDoc ignored) {
322         } catch (SecurityException JavaDoc ignored) {
323         }
324
325         if (field != null && Throwable JavaDoc.class.isAssignableFrom(field.getType())) {
326             try {
327                 return (Throwable JavaDoc) field.get(throwable);
328             } catch (IllegalAccessException JavaDoc ignored) {
329             } catch (IllegalArgumentException JavaDoc ignored) {
330             }
331         }
332         return null;
333     }
334
335     //-----------------------------------------------------------------------
336
/**
337      * <p>Checks if the Throwable class has a <code>getCause</code> method.</p>
338      *
339      * <p>This is true for JDK 1.4 and above.</p>
340      *
341      * @return true if Throwable is nestable
342      * @since 2.0
343      */

344     public static boolean isThrowableNested() {
345         return THROWABLE_CAUSE_METHOD != null;
346     }
347     
348     /**
349      * <p>Checks whether this <code>Throwable</code> class can store a cause.</p>
350      *
351      * <p>This method does <b>not</b> check whether it actually does store a cause.<p>
352      *
353      * @param throwable the <code>Throwable</code> to examine, may be null
354      * @return boolean <code>true</code> if nested otherwise <code>false</code>
355      * @since 2.0
356      */

357     public static boolean isNestedThrowable(Throwable JavaDoc throwable) {
358         if (throwable == null) {
359             return false;
360         }
361
362         if (throwable instanceof Nestable) {
363             return true;
364         } else if (throwable instanceof SQLException JavaDoc) {
365             return true;
366         } else if (throwable instanceof InvocationTargetException JavaDoc) {
367             return true;
368         } else if (isThrowableNested()) {
369             return true;
370         }
371
372         Class JavaDoc cls = throwable.getClass();
373         for (int i = 0, isize = CAUSE_METHOD_NAMES.length; i < isize; i++) {
374             try {
375                 Method JavaDoc method = cls.getMethod(CAUSE_METHOD_NAMES[i], null);
376                 if (method != null && Throwable JavaDoc.class.isAssignableFrom(method.getReturnType())) {
377                     return true;
378                 }
379             } catch (NoSuchMethodException JavaDoc ignored) {
380             } catch (SecurityException JavaDoc ignored) {
381             }
382         }
383
384         try {
385             Field JavaDoc field = cls.getField("detail");
386             if (field != null) {
387                 return true;
388             }
389         } catch (NoSuchFieldException JavaDoc ignored) {
390         } catch (SecurityException JavaDoc ignored) {
391         }
392
393         return false;
394     }
395
396     //-----------------------------------------------------------------------
397
/**
398      * <p>Counts the number of <code>Throwable</code> objects in the
399      * exception chain.</p>
400      *
401      * <p>A throwable without cause will return <code>1</code>.
402      * A throwable with one cause will return <code>2</code> and so on.
403      * A <code>null</code> throwable will return <code>0</code>.</p>
404      *
405      * @param throwable the throwable to inspect, may be null
406      * @return the count of throwables, zero if null input
407      */

408     public static int getThrowableCount(Throwable JavaDoc throwable) {
409         int count = 0;
410         while (throwable != null) {
411             count++;
412             throwable = ExceptionUtils.getCause(throwable);
413         }
414         return count;
415     }
416
417     /**
418      * <p>Returns the list of <code>Throwable</code> objects in the
419      * exception chain.</p>
420      *
421      * <p>A throwable without cause will return an array containing
422      * one element - the input throwable.
423      * A throwable with one cause will return an array containing
424      * two elements. - the input throwable and the cause throwable.
425      * A <code>null</code> throwable will return an array size zero.</p>
426      *
427      * @param throwable the throwable to inspect, may be null
428      * @return the array of throwables, never null
429      */

430     public static Throwable JavaDoc[] getThrowables(Throwable JavaDoc throwable) {
431         List JavaDoc list = new ArrayList JavaDoc();
432         while (throwable != null) {
433             list.add(throwable);
434             throwable = ExceptionUtils.getCause(throwable);
435         }
436         return (Throwable JavaDoc[]) list.toArray(new Throwable JavaDoc[list.size()]);
437     }
438
439     //-----------------------------------------------------------------------
440
/**
441      * <p>Returns the (zero based) index of the first <code>Throwable</code>
442      * that matches the specified class (exactly) in the exception chain.
443      * Subclasses of the specified class do not match - see
444      * {@link #indexOfType(Throwable, Class)} for the opposite.</p>
445      *
446      * <p>A <code>null</code> throwable returns <code>-1</code>.
447      * A <code>null</code> type returns <code>-1</code>.
448      * No match in the chain returns <code>-1</code>.</p>
449      *
450      * @param throwable the throwable to inspect, may be null
451      * @param clazz the class to search for, subclasses do not match, null returns -1
452      * @return the index into the throwable chain, -1 if no match or null input
453      */

454     public static int indexOfThrowable(Throwable JavaDoc throwable, Class JavaDoc clazz) {
455         return indexOf(throwable, clazz, 0, false);
456     }
457
458     /**
459      * <p>Returns the (zero based) index of the first <code>Throwable</code>
460      * that matches the specified type in the exception chain from
461      * a specified index.
462      * Subclasses of the specified class do not match - see
463      * {@link #indexOfType(Throwable, Class, int)} for the opposite.</p>
464      *
465      * <p>A <code>null</code> throwable returns <code>-1</code>.
466      * A <code>null</code> type returns <code>-1</code>.
467      * No match in the chain returns <code>-1</code>.
468      * A negative start index is treated as zero.
469      * A start index greater than the number of throwables returns <code>-1</code>.</p>
470      *
471      * @param throwable the throwable to inspect, may be null
472      * @param clazz the class to search for, subclasses do not match, null returns -1
473      * @param fromIndex the (zero based) index of the starting position,
474      * negative treated as zero, larger than chain size returns -1
475      * @return the index into the throwable chain, -1 if no match or null input
476      */

477     public static int indexOfThrowable(Throwable JavaDoc throwable, Class JavaDoc clazz, int fromIndex) {
478         return indexOf(throwable, clazz, fromIndex, false);
479     }
480
481     //-----------------------------------------------------------------------
482
/**
483      * <p>Returns the (zero based) index of the first <code>Throwable</code>
484      * that matches the specified class or subclass in the exception chain.
485      * Subclasses of the specified class do match - see
486      * {@link #indexOfThrowable(Throwable, Class)} for the opposite.</p>
487      *
488      * <p>A <code>null</code> throwable returns <code>-1</code>.
489      * A <code>null</code> type returns <code>-1</code>.
490      * No match in the chain returns <code>-1</code>.</p>
491      *
492      * @param throwable the throwable to inspect, may be null
493      * @param type the type to search for, subclasses match, null returns -1
494      * @return the index into the throwable chain, -1 if no match or null input
495      * @since 2.1
496      */

497     public static int indexOfType(Throwable JavaDoc throwable, Class JavaDoc type) {
498         return indexOf(throwable, type, 0, true);
499     }
500
501     /**
502      * <p>Returns the (zero based) index of the first <code>Throwable</code>
503      * that matches the specified type in the exception chain from
504      * a specified index.
505      * Subclasses of the specified class do match - see
506      * {@link #indexOfThrowable(Throwable, Class)} for the opposite.</p>
507      *
508      * <p>A <code>null</code> throwable returns <code>-1</code>.
509      * A <code>null</code> type returns <code>-1</code>.
510      * No match in the chain returns <code>-1</code>.
511      * A negative start index is treated as zero.
512      * A start index greater than the number of throwables returns <code>-1</code>.</p>
513      *
514      * @param throwable the throwable to inspect, may be null
515      * @param type the type to search for, subclasses match, null returns -1
516      * @param fromIndex the (zero based) index of the starting position,
517      * negative treated as zero, larger than chain size returns -1
518      * @return the index into the throwable chain, -1 if no match or null input
519      * @since 2.1
520      */

521     public static int indexOfType(Throwable JavaDoc throwable, Class JavaDoc type, int fromIndex) {
522         return indexOf(throwable, type, fromIndex, true);
523     }
524
525     private static int indexOf(Throwable JavaDoc throwable, Class JavaDoc type, int fromIndex, boolean subclass) {
526         if (throwable == null || type == null) {
527             return -1;
528         }
529         if (fromIndex < 0) {
530             fromIndex = 0;
531         }
532         Throwable JavaDoc[] throwables = ExceptionUtils.getThrowables(throwable);
533         if (fromIndex >= throwables.length) {
534             return -1;
535         }
536         if (subclass) {
537             for (int i = fromIndex; i < throwables.length; i++) {
538                 if (type.isAssignableFrom(throwables[i].getClass())) {
539                     return i;
540                 }
541             }
542         } else {
543             for (int i = fromIndex; i < throwables.length; i++) {
544                 if (type.equals(throwables[i].getClass())) {
545                     return i;
546                 }
547             }
548         }
549         return -1;
550     }
551
552     //-----------------------------------------------------------------------
553
/**
554      * <p>Prints a compact stack trace for the root cause of a throwable
555      * to <code>System.err</code>.</p>
556      *
557      * <p>The compact stack trace starts with the root cause and prints
558      * stack frames up to the place where it was caught and wrapped.
559      * Then it prints the wrapped exception and continues with stack frames
560      * until the wrapper exception is caught and wrapped again, etc.</p>
561      *
562      * <p>The method is equivalent to <code>printStackTrace</code> for throwables
563      * that don't have nested causes.</p>
564      *
565      * @param throwable the throwable to output
566      * @since 2.0
567      */

568     public static void printRootCauseStackTrace(Throwable JavaDoc throwable) {
569         printRootCauseStackTrace(throwable, System.err);
570     }
571
572     /**
573      * <p>Prints a compact stack trace for the root cause of a throwable.</p>
574      *
575      * <p>The compact stack trace starts with the root cause and prints
576      * stack frames up to the place where it was caught and wrapped.
577      * Then it prints the wrapped exception and continues with stack frames
578      * until the wrapper exception is caught and wrapped again, etc.</p>
579      *
580      * <p>The method is equivalent to <code>printStackTrace</code> for throwables
581      * that don't have nested causes.</p>
582      *
583      * @param throwable the throwable to output, may be null
584      * @param stream the stream to output to, may not be null
585      * @throws IllegalArgumentException if the stream is <code>null</code>
586      * @since 2.0
587      */

588     public static void printRootCauseStackTrace(Throwable JavaDoc throwable, PrintStream JavaDoc stream) {
589         if (throwable == null) {
590             return;
591         }
592         if (stream == null) {
593             throw new IllegalArgumentException JavaDoc("The PrintStream must not be null");
594         }
595         String JavaDoc trace[] = getRootCauseStackTrace(throwable);
596         for (int i = 0; i < trace.length; i++) {
597             stream.println(trace[i]);
598         }
599         stream.flush();
600     }
601
602     /**
603      * <p>Prints a compact stack trace for the root cause of a throwable.</p>
604      *
605      * <p>The compact stack trace starts with the root cause and prints
606      * stack frames up to the place where it was caught and wrapped.
607      * Then it prints the wrapped exception and continues with stack frames
608      * until the wrapper exception is caught and wrapped again, etc.</p>
609      *
610      * <p>The method is equivalent to <code>printStackTrace</code> for throwables
611      * that don't have nested causes.</p>
612      *
613      * @param throwable the throwable to output, may be null
614      * @param writer the writer to output to, may not be null
615      * @throws IllegalArgumentException if the writer is <code>null</code>
616      * @since 2.0
617      */

618     public static void printRootCauseStackTrace(Throwable JavaDoc throwable, PrintWriter JavaDoc writer) {
619         if (throwable == null) {
620             return;
621         }
622         if (writer == null) {
623             throw new IllegalArgumentException JavaDoc("The PrintWriter must not be null");
624         }
625         String JavaDoc trace[] = getRootCauseStackTrace(throwable);
626         for (int i = 0; i < trace.length; i++) {
627             writer.println(trace[i]);
628         }
629         writer.flush();
630     }
631
632     //-----------------------------------------------------------------------
633
/**
634      * <p>Creates a compact stack trace for the root cause of the supplied
635      * <code>Throwable</code>.</p>
636      *
637      * @param throwable the throwable to examine, may be null
638      * @return an array of stack trace frames, never null
639      * @since 2.0
640      */

641     public static String JavaDoc[] getRootCauseStackTrace(Throwable JavaDoc throwable) {
642         if (throwable == null) {
643             return ArrayUtils.EMPTY_STRING_ARRAY;
644         }
645         Throwable JavaDoc throwables[] = getThrowables(throwable);
646         int count = throwables.length;
647         ArrayList JavaDoc frames = new ArrayList JavaDoc();
648         List JavaDoc nextTrace = getStackFrameList(throwables[count - 1]);
649         for (int i = count; --i >= 0;) {
650             List JavaDoc trace = nextTrace;
651             if (i != 0) {
652                 nextTrace = getStackFrameList(throwables[i - 1]);
653                 removeCommonFrames(trace, nextTrace);
654             }
655             if (i == count - 1) {
656                 frames.add(throwables[i].toString());
657             } else {
658                 frames.add(WRAPPED_MARKER + throwables[i].toString());
659             }
660             for (int j = 0; j < trace.size(); j++) {
661                 frames.add(trace.get(j));
662             }
663         }
664         return (String JavaDoc[]) frames.toArray(new String JavaDoc[0]);
665     }
666
667     /**
668      * <p>Removes common frames from the cause trace given the two stack traces.</p>
669      *
670      * @param causeFrames stack trace of a cause throwable
671      * @param wrapperFrames stack trace of a wrapper throwable
672      * @throws IllegalArgumentException if either argument is null
673      * @since 2.0
674      */

675     public static void removeCommonFrames(List JavaDoc causeFrames, List JavaDoc wrapperFrames) {
676         if (causeFrames == null || wrapperFrames == null) {
677             throw new IllegalArgumentException JavaDoc("The List must not be null");
678         }
679         int causeFrameIndex = causeFrames.size() - 1;
680         int wrapperFrameIndex = wrapperFrames.size() - 1;
681         while (causeFrameIndex >= 0 && wrapperFrameIndex >= 0) {
682             // Remove the frame from the cause trace if it is the same
683
// as in the wrapper trace
684
String JavaDoc causeFrame = (String JavaDoc) causeFrames.get(causeFrameIndex);
685             String JavaDoc wrapperFrame = (String JavaDoc) wrapperFrames.get(wrapperFrameIndex);
686             if (causeFrame.equals(wrapperFrame)) {
687                 causeFrames.remove(causeFrameIndex);
688             }
689             causeFrameIndex--;
690             wrapperFrameIndex--;
691         }
692     }
693
694     //-----------------------------------------------------------------------
695
/**
696      * <p>Gets the stack trace from a Throwable as a String.</p>
697      *
698      * @param throwable the <code>Throwable</code> to be examined
699      * @return the stack trace as generated by the exception's
700      * <code>printStackTrace(PrintWriter)</code> method
701      */

702     public static String JavaDoc getStackTrace(Throwable JavaDoc throwable) {
703         StringWriter JavaDoc sw = new StringWriter JavaDoc();
704         PrintWriter JavaDoc pw = new PrintWriter JavaDoc(sw, true);
705         throwable.printStackTrace(pw);
706         return sw.getBuffer().toString();
707     }
708
709     /**
710      * <p>A way to get the entire nested stack-trace of an throwable.</p>
711      *
712      * @param throwable the <code>Throwable</code> to be examined
713      * @return the nested stack trace, with the root cause first
714      * @since 2.0
715      */

716     public static String JavaDoc getFullStackTrace(Throwable JavaDoc throwable) {
717         StringWriter JavaDoc sw = new StringWriter JavaDoc();
718         PrintWriter JavaDoc pw = new PrintWriter JavaDoc(sw, true);
719         Throwable JavaDoc[] ts = getThrowables(throwable);
720         for (int i = 0; i < ts.length; i++) {
721             ts[i].printStackTrace(pw);
722             if (isNestedThrowable(ts[i])) {
723                 break;
724             }
725         }
726         return sw.getBuffer().toString();
727     }
728
729     //-----------------------------------------------------------------------
730
/**
731      * <p>Captures the stack trace associated with the specified
732      * <code>Throwable</code> object, decomposing it into a list of
733      * stack frames.</p>
734      *
735      * @param throwable the <code>Throwable</code> to examine, may be null
736      * @return an array of strings describing each stack frame, never null
737      */

738     public static String JavaDoc[] getStackFrames(Throwable JavaDoc throwable) {
739         if (throwable == null) {
740             return ArrayUtils.EMPTY_STRING_ARRAY;
741         }
742         return getStackFrames(getStackTrace(throwable));
743     }
744
745     /**
746      * <p>Returns an array where each element is a line from the argument.</p>
747      * <p>The end of line is determined by the value of {@link SystemUtils#LINE_SEPARATOR}.</p>
748      *
749      * <p>Functionality shared between the
750      * <code>getStackFrames(Throwable)</code> methods of this and the
751      * {@link org.apache.commons.lang.exception.NestableDelegate}
752      * classes.</p>
753      * @param stackTrace A stack trace String.
754      * @return an array where each element is a line from the argument.
755      */

756     static String JavaDoc[] getStackFrames(String JavaDoc stackTrace) {
757         String JavaDoc linebreak = SystemUtils.LINE_SEPARATOR;
758         StringTokenizer JavaDoc frames = new StringTokenizer JavaDoc(stackTrace, linebreak);
759         List JavaDoc list = new LinkedList JavaDoc();
760         while (frames.hasMoreTokens()) {
761             list.add(frames.nextToken());
762         }
763         return toArray(list);
764     }
765
766     /**
767      * <p>Produces a <code>List</code> of stack frames - the message
768      * is not included.</p>
769      *
770      * <p>This works in most cases - it will only fail if the exception
771      * message contains a line that starts with:
772      * <code>&quot;&nbsp;&nbsp;&nbsp;at&quot;.</code></p>
773      *
774      * @param t is any throwable
775      * @return List of stack frames
776      */

777     static List JavaDoc getStackFrameList(Throwable JavaDoc t) {
778         String JavaDoc stackTrace = getStackTrace(t);
779         String JavaDoc linebreak = SystemUtils.LINE_SEPARATOR;
780         StringTokenizer JavaDoc frames = new StringTokenizer JavaDoc(stackTrace, linebreak);
781         List JavaDoc list = new LinkedList JavaDoc();
782         boolean traceStarted = false;
783         while (frames.hasMoreTokens()) {
784             String JavaDoc token = frames.nextToken();
785             // Determine if the line starts with <whitespace>at
786
int at = token.indexOf("at");
787             if (at != -1 && token.substring(0, at).trim().length() == 0) {
788                 traceStarted = true;
789                 list.add(token);
790             } else if (traceStarted) {
791                 break;
792             }
793         }
794         return list;
795     }
796     
797 }
798
Popular Tags