Source code: org/apache/commons/lang/exception/NestableDelegate.java
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;
19 import java.io.PrintWriter;
20 import java.io.Serializable;
21 import java.io.StringWriter;
22 import java.util.ArrayList;
23 import java.util.Arrays;
24 import java.util.Collections;
25 import java.util.Iterator;
26 import java.util.List;
27
28 /**
29 * <p>A shared implementation of the nestable exception functionality.</p>
30 * <p>
31 * The code is shared between
32 * {@link org.apache.commons.lang.exception.NestableError NestableError},
33 * {@link org.apache.commons.lang.exception.NestableException NestableException} and
34 * {@link org.apache.commons.lang.exception.NestableRuntimeException NestableRuntimeException}.
35 * </p>
36 *
37 * @author <a href="mailto:Rafal.Krzewski@e-point.pl">Rafal Krzewski</a>
38 * @author <a href="mailto:dlr@collab.net">Daniel Rall</a>
39 * @author <a href="mailto:knielsen@apache.org">Kasper Nielsen</a>
40 * @author <a href="mailto:steven@caswell.name">Steven Caswell</a>
41 * @author Sean C. Sullivan
42 * @author Stephen Colebourne
43 * @since 1.0
44 * @version $Id: NestableDelegate.java 161243 2005-04-14 04:30:28Z ggregory $
45 */
46 public class NestableDelegate implements Serializable {
47
48 /**
49 * Constructor error message.
50 */
51 private transient static final String MUST_BE_THROWABLE =
52 "The Nestable implementation passed to the NestableDelegate(Nestable) "
53 + "constructor must extend java.lang.Throwable";
54
55 /**
56 * Holds the reference to the exception or error that we're
57 * wrapping (which must be a {@link
58 * org.apache.commons.lang.exception.Nestable} implementation).
59 */
60 private Throwable nestable = null;
61
62 /**
63 * Whether to print the stack trace top-down.
64 * This public flag may be set by calling code, typically in initialisation.
65 * This exists for backwards compatability, setting it to false will return
66 * the library to v1.0 behaviour (but will affect all users of the library
67 * in the classloader).
68 * @since 2.0
69 */
70 public static boolean topDown = true;
71
72 /**
73 * Whether to trim the repeated stack trace.
74 * This public flag may be set by calling code, typically in initialisation.
75 * This exists for backwards compatability, setting it to false will return
76 * the library to v1.0 behaviour (but will affect all users of the library
77 * in the classloader).
78 * @since 2.0
79 */
80 public static boolean trimStackFrames = true;
81
82 /**
83 * Whether to match subclasses via indexOf.
84 * This public flag may be set by calling code, typically in initialisation.
85 * This exists for backwards compatability, setting it to false will return
86 * the library to v2.0 behaviour (but will affect all users of the library
87 * in the classloader).
88 * @since 2.1
89 */
90 public static boolean matchSubclasses = true;
91
92 /**
93 * Constructs a new <code>NestableDelegate</code> instance to manage the
94 * specified <code>Nestable</code>.
95 *
96 * @param nestable the Nestable implementation (<i>must</i> extend
97 * {@link java.lang.Throwable})
98 * @since 2.0
99 */
100 public NestableDelegate(Nestable nestable) {
101 if (nestable instanceof Throwable) {
102 this.nestable = (Throwable) nestable;
103 } else {
104 throw new IllegalArgumentException(MUST_BE_THROWABLE);
105 }
106 }
107
108 /**
109 * Returns the error message of the <code>Throwable</code> in the chain
110 * of <code>Throwable</code>s at the specified index, numbered from 0.
111 *
112 * @param index the index of the <code>Throwable</code> in the chain of
113 * <code>Throwable</code>s
114 * @return the error message, or null if the <code>Throwable</code> at the
115 * specified index in the chain does not contain a message
116 * @throws IndexOutOfBoundsException if the <code>index</code> argument is
117 * negative or not less than the count of <code>Throwable</code>s in the
118 * chain
119 * @since 2.0
120 */
121 public String getMessage(int index) {
122 Throwable t = this.getThrowable(index);
123 if (Nestable.class.isInstance(t)) {
124 return ((Nestable) t).getMessage(0);
125 } else {
126 return t.getMessage();
127 }
128 }
129
130 /**
131 * Returns the full message contained by the <code>Nestable</code>
132 * and any nested <code>Throwable</code>s.
133 *
134 * @param baseMsg the base message to use when creating the full
135 * message. Should be generally be called via
136 * <code>nestableHelper.getMessage(super.getMessage())</code>,
137 * where <code>super</code> is an instance of {@link
138 * java.lang.Throwable}.
139 * @return The concatenated message for this and all nested
140 * <code>Throwable</code>s
141 * @since 2.0
142 */
143 public String getMessage(String baseMsg) {
144 StringBuffer msg = new StringBuffer();
145 if (baseMsg != null) {
146 msg.append(baseMsg);
147 }
148
149 Throwable nestedCause = ExceptionUtils.getCause(this.nestable);
150 if (nestedCause != null) {
151 String causeMsg = nestedCause.getMessage();
152 if (causeMsg != null) {
153 if (baseMsg != null) {
154 msg.append(": ");
155 }
156 msg.append(causeMsg);
157 }
158
159 }
160 return msg.length() > 0 ? msg.toString() : null;
161 }
162
163 /**
164 * Returns the error message of this and any nested <code>Throwable</code>s
165 * in an array of Strings, one element for each message. Any
166 * <code>Throwable</code> not containing a message is represented in the
167 * array by a null. This has the effect of cause the length of the returned
168 * array to be equal to the result of the {@link #getThrowableCount()}
169 * operation.
170 *
171 * @return the error messages
172 * @since 2.0
173 */
174 public String[] getMessages() {
175 Throwable[] throwables = this.getThrowables();
176 String[] msgs = new String[throwables.length];
177 for (int i = 0; i < throwables.length; i++) {
178 msgs[i] =
179 (Nestable.class.isInstance(throwables[i])
180 ? ((Nestable) throwables[i]).getMessage(0)
181 : throwables[i].getMessage());
182 }
183 return msgs;
184 }
185
186 /**
187 * Returns the <code>Throwable</code> in the chain of
188 * <code>Throwable</code>s at the specified index, numbered from 0.
189 *
190 * @param index the index, numbered from 0, of the <code>Throwable</code> in
191 * the chain of <code>Throwable</code>s
192 * @return the <code>Throwable</code>
193 * @throws IndexOutOfBoundsException if the <code>index</code> argument is
194 * negative or not less than the count of <code>Throwable</code>s in the
195 * chain
196 * @since 2.0
197 */
198 public Throwable getThrowable(int index) {
199 if (index == 0) {
200 return this.nestable;
201 }
202 Throwable[] throwables = this.getThrowables();
203 return throwables[index];
204 }
205
206 /**
207 * Returns the number of <code>Throwable</code>s contained in the
208 * <code>Nestable</code> contained by this delegate.
209 *
210 * @return the throwable count
211 * @since 2.0
212 */
213 public int getThrowableCount() {
214 return ExceptionUtils.getThrowableCount(this.nestable);
215 }
216
217 /**
218 * Returns this delegate's <code>Nestable</code> and any nested
219 * <code>Throwable</code>s in an array of <code>Throwable</code>s, one
220 * element for each <code>Throwable</code>.
221 *
222 * @return the <code>Throwable</code>s
223 * @since 2.0
224 */
225 public Throwable[] getThrowables() {
226 return ExceptionUtils.getThrowables(this.nestable);
227 }
228
229 /**
230 * Returns the index, numbered from 0, of the first <code>Throwable</code>
231 * that matches the specified type, or a subclass, in the chain of <code>Throwable</code>s
232 * with an index greater than or equal to the specified index.
233 * The method returns -1 if the specified type is not found in the chain.
234 * <p>
235 * NOTE: From v2.1, we have clarified the <code>Nestable</code> interface
236 * such that this method matches subclasses.
237 * If you want to NOT match subclasses, please use
238 * {@link ExceptionUtils#indexOfThrowable(Throwable, Class, int)}
239 * (which is avaiable in all versions of lang).
240 * An alternative is to use the public static flag {@link #matchSubclasses}
241 * on <code>NestableDelegate</code>, however this is not recommended.
242 *
243 * @param type the type to find, subclasses match, null returns -1
244 * @param fromIndex the index, numbered from 0, of the starting position in
245 * the chain to be searched
246 * @return index of the first occurrence of the type in the chain, or -1 if
247 * the type is not found
248 * @throws IndexOutOfBoundsException if the <code>fromIndex</code> argument
249 * is negative or not less than the count of <code>Throwable</code>s in the
250 * chain
251 * @since 2.0
252 */
253 public int indexOfThrowable(Class type, int fromIndex) {
254 if (type == null) {
255 return -1;
256 }
257 if (fromIndex < 0) {
258 throw new IndexOutOfBoundsException("The start index was out of bounds: " + fromIndex);
259 }
260 Throwable[] throwables = ExceptionUtils.getThrowables(this.nestable);
261 if (fromIndex >= throwables.length) {
262 throw new IndexOutOfBoundsException("The start index was out of bounds: "
263 + fromIndex + " >= " + throwables.length);
264 }
265 if (matchSubclasses) {
266 for (int i = fromIndex; i < throwables.length; i++) {
267 if (type.isAssignableFrom(throwables[i].getClass())) {
268 return i;
269 }
270 }
271 } else {
272 for (int i = fromIndex; i < throwables.length; i++) {
273 if (type.equals(throwables[i].getClass())) {
274 return i;
275 }
276 }
277 }
278 return -1;
279 }
280
281 /**
282 * Prints the stack trace of this exception the the standar error
283 * stream.
284 */
285 public void printStackTrace() {
286 printStackTrace(System.err);
287 }
288
289 /**
290 * Prints the stack trace of this exception to the specified
291 * stream.
292 *
293 * @param out <code>PrintStream</code> to use for output.
294 * @see #printStackTrace(PrintWriter)
295 */
296 public void printStackTrace(PrintStream out) {
297 synchronized (out) {
298 PrintWriter pw = new PrintWriter(out, false);
299 printStackTrace(pw);
300 // Flush the PrintWriter before it's GC'ed.
301 pw.flush();
302 }
303 }
304
305 /**
306 * Prints the stack trace of this exception to the specified
307 * writer. If the Throwable class has a <code>getCause</code>
308 * method (i.e. running on jre1.4 or higher), this method just
309 * uses Throwable's printStackTrace() method. Otherwise, generates
310 * the stack-trace, by taking into account the 'topDown' and
311 * 'trimStackFrames' parameters. The topDown and trimStackFrames
312 * are set to 'true' by default (produces jre1.4-like stack trace).
313 *
314 * @param out <code>PrintWriter</code> to use for output.
315 */
316 public void printStackTrace(PrintWriter out) {
317 Throwable throwable = this.nestable;
318 // if running on jre1.4 or higher, use default printStackTrace
319 if (ExceptionUtils.isThrowableNested()) {
320 if (throwable instanceof Nestable) {
321 ((Nestable)throwable).printPartialStackTrace(out);
322 } else {
323 throwable.printStackTrace(out);
324 }
325 return;
326 }
327
328 // generating the nested stack trace
329 List stacks = new ArrayList();
330 while (throwable != null) {
331 String[] st = getStackFrames(throwable);
332 stacks.add(st);
333 throwable = ExceptionUtils.getCause(throwable);
334 }
335
336 // If NOT topDown, reverse the stack
337 String separatorLine = "Caused by: ";
338 if (!topDown) {
339 separatorLine = "Rethrown as: ";
340 Collections.reverse(stacks);
341 }
342
343 // Remove the repeated lines in the stack
344 if (trimStackFrames) {
345 trimStackFrames(stacks);
346 }
347
348 synchronized (out) {
349 for (Iterator iter=stacks.iterator(); iter.hasNext();) {
350 String[] st = (String[]) iter.next();
351 for (int i=0, len=st.length; i < len; i++) {
352 out.println(st[i]);
353 }
354 if (iter.hasNext()) {
355 out.print(separatorLine);
356 }
357 }
358 }
359 }
360
361 /**
362 * Captures the stack trace associated with the specified
363 * <code>Throwable</code> object, decomposing it into a list of
364 * stack frames.
365 *
366 * @param t The <code>Throwable</code>.
367 * @return An array of strings describing each stack frame.
368 * @since 2.0
369 */
370 protected String[] getStackFrames(Throwable t) {
371 StringWriter sw = new StringWriter();
372 PrintWriter pw = new PrintWriter(sw, true);
373
374 // Avoid infinite loop between decompose() and printStackTrace().
375 if (t instanceof Nestable) {
376 ((Nestable) t).printPartialStackTrace(pw);
377 } else {
378 t.printStackTrace(pw);
379 }
380 return ExceptionUtils.getStackFrames(sw.getBuffer().toString());
381 }
382
383 /**
384 * Trims the stack frames. The first set is left untouched. The rest
385 * of the frames are truncated from the bottom by comparing with
386 * one just on top.
387 *
388 * @param stacks The list containing String[] elements
389 * @since 2.0
390 */
391 protected void trimStackFrames(List stacks) {
392 for (int size=stacks.size(), i=size-1; i > 0; i--) {
393 String[] curr = (String[]) stacks.get(i);
394 String[] next = (String[]) stacks.get(i-1);
395
396 List currList = new ArrayList(Arrays.asList(curr));
397 List nextList = new ArrayList(Arrays.asList(next));
398 ExceptionUtils.removeCommonFrames(currList, nextList);
399
400 int trimmed = curr.length - currList.size();
401 if (trimmed > 0) {
402 currList.add("\t... "+trimmed+" more");
403 stacks.set(
404 i,
405 currList.toArray(new String[currList.size()])
406 );
407 }
408 }
409 }
410 }