KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > log > format > ExceptionUtil


1 /* ====================================================================
2  * The Apache Software License, Version 1.1
3  *
4  * Copyright (c) 1997-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,
20  * if any, must include the following acknowledgment:
21  * "This product includes software developed by the
22  * Apache Software Foundation (http://www.apache.org/)."
23  * Alternately, this acknowledgment may appear in the software
24  * itself, if and wherever such third-party acknowledgments
25  * normally appear.
26  *
27  * 4. The names "Jakarta", "Avalon", and "Apache Software Foundation"
28  * must not be used to endorse or promote products derived from this
29  * software without prior written permission. For written
30  * permission, please contact apache@apache.org.
31  *
32  * 5. Products derived from this software may not be called "Apache",
33  * nor may "Apache" appear in their name, without prior written
34  * permission of the Apache Software Foundation.
35  *
36  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
37  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
38  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
39  * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
40  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
41  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
42  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
43  * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
44  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
45  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
46  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
47  * SUCH DAMAGE.
48  * ====================================================================
49  *
50  * This software consists of voluntary contributions made by many
51  * individuals on behalf of the Apache Software Foundation. For more
52  * information on the Apache Software Foundation, please see
53  * <http://www.apache.org/>.
54  */

55 package org.apache.log.format;
56
57 import java.io.PrintWriter JavaDoc;
58 import java.io.StringWriter JavaDoc;
59 import java.lang.reflect.Method JavaDoc;
60 import java.util.StringTokenizer JavaDoc;
61
62 /**
63  * This class provides basic facilities for manipulating exceptions.
64  *
65  * Some exception handling stuff thieved from Turbine...
66  *
67  * @deprecated use org.apache.avalon.framework.ExceptionUtil instead
68  *
69  * @author <a HREF="mailto:dev@avalon.apache.org">Avalon Development Team</a>
70  * @version 1.0
71  */

72 final class ExceptionUtil
73 {
74     private static final String JavaDoc LINE_SEPARATOR = System.getProperty( "line.separator" );
75     private static final String JavaDoc GET_CAUSE_NAME = "getCause";
76     private static final Class JavaDoc[] GET_CAUSE_PARAMTYPES = new Class JavaDoc[ 0 ];
77     private static final Class JavaDoc CASCADING_INTERFACE;
78
79     static
80     {
81         Class JavaDoc klass = null;
82         try
83         {
84             klass = Class.forName("org.apache.avalon.framework.CascadingThrowable");
85         }
86         catch (Exception JavaDoc e)
87         {
88             // class not available
89
klass = null;
90         }
91
92         CASCADING_INTERFACE = klass;
93     }
94
95     /**
96      * Private constructor to prevent instantiation.
97      */

98     private ExceptionUtil()
99     {
100     }
101
102     /**
103      * Generate string for specified exception and the cause of
104      * this exception (if any).
105      * @param throwable a <code>Throwable</code>
106      * @return the stack trace as a <code>String</code>
107      */

108     public static String JavaDoc printStackTrace( final Throwable JavaDoc throwable )
109     {
110         return printStackTrace( throwable, 0, true );
111     }
112
113     /**
114      * Generate string for specified exception and if printCascading
115      * is true will print all cascading exceptions.
116      * @param throwable a <code>Throwable</code>
117      * @param printCascading if <code>true</code> will print all cascading exceptions
118      * @return the stack trace as a <code>String</code>
119      */

120     public static String JavaDoc printStackTrace( final Throwable JavaDoc throwable,
121                                           final boolean printCascading )
122     {
123         return printStackTrace( throwable, 0, printCascading );
124     }
125
126     /**
127      * Serialize the specified <code>Throwable</code> to a string.
128      * Restrict the number of frames printed out to the specified depth.
129      * If the depth specified is <code>0</code> then all the frames are
130      * converted into a string.
131      * @param throwable a <code>Throwable</code>
132      * @param depth number of stack trace frames to show
133      * @return the stack trace as a <code>String</code>
134      */

135     public static String JavaDoc printStackTrace( final Throwable JavaDoc throwable, final int depth )
136     {
137         int dp = depth;
138         final String JavaDoc[] lines = captureStackTrace( throwable );
139
140         if( 0 == dp || dp > lines.length )
141         {
142             dp = lines.length;
143         }
144
145         final StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
146
147         for( int i = 0; i < dp; i++ )
148         {
149             sb.append( lines[ i ] );
150             sb.append( LINE_SEPARATOR );
151         }
152
153         return sb.toString();
154     }
155
156     /**
157      * Generate exception string for specified exception to specified depth
158      * and all Cascading exceptions if printCascading is true.
159      * @param throwable a <code>Throwable</code>
160      * @param depth number of stack trace frames to show
161      * @param printCascading if <code>true</code> will print all cascading exceptions
162      * @return the stack trace as a <code>String</code>
163      */

164     public static String JavaDoc printStackTrace( final Throwable JavaDoc throwable,
165                                           final int depth,
166                                           final boolean printCascading )
167     {
168         return printStackTrace( throwable, depth, printCascading, true );
169     }
170
171     /**
172      * Generate exception string for specified exception to specified depth
173      * and all Cascading exceptions if printCascading is true. If useReflection
174      * is true then the method will also attempt to use reflection to find a
175      * method with signature <code>Throwable getCause()</code>. This makes
176      * it compatible with JDK1.4 mechanisms for nesting exceptions.
177      * @param throwable a <code>Throwable</code>
178      * @param depth number of stack trace frames to show
179      * @param printCascading if <code>true</code> will print all cascading exceptions
180      * @param useReflection if <code>true</code> will use reflection to handle JDK1.4
181      * nested exceptions
182      * @return the stack trace as a <code>String</code>
183      */

184     public static String JavaDoc printStackTrace( final Throwable JavaDoc throwable,
185                                           final int depth,
186                                           final boolean printCascading,
187                                           final boolean useReflection )
188     {
189         final String JavaDoc result = printStackTrace( throwable, depth );
190
191         if( !printCascading )
192         {
193             return result;
194         }
195         else
196         {
197             final StringBuffer JavaDoc sb = new StringBuffer JavaDoc();
198             sb.append( result );
199
200             Throwable JavaDoc cause = getCause( throwable, useReflection );
201
202             while( null != cause )
203             {
204                 sb.append( "rethrown from" );
205                 sb.append( LINE_SEPARATOR );
206                 sb.append( printStackTrace( cause, depth ) );
207
208                 cause = getCause( cause, useReflection );
209             }
210
211             return sb.toString();
212         }
213     }
214
215     /**
216      * Utility method to get cause of exception.
217      * @param throwable a <code>Throwable</code>
218      * @param useReflection if <code>true</code> will use reflection to handle JDK1.4
219      * nested exceptions
220      * @return cause of specified exception
221      */

222     public static Throwable JavaDoc getCause( final Throwable JavaDoc throwable,
223                                       final boolean useReflection )
224     {
225         if( useReflection ||
226             ( null != CASCADING_INTERFACE &&
227                 CASCADING_INTERFACE.isAssignableFrom(throwable.getClass()) ) )
228         {
229             try
230             {
231                 final Class JavaDoc clazz = throwable.getClass();
232                 final Method JavaDoc method =
233                     clazz.getMethod( GET_CAUSE_NAME, GET_CAUSE_PARAMTYPES );
234                 return (Throwable JavaDoc)method.invoke( throwable, null );
235             }
236             catch( final Throwable JavaDoc t )
237             {
238                 return null;
239             }
240         }
241         else
242         {
243             return null;
244         }
245     }
246
247     /**
248      * Captures the stack trace associated with this exception.
249      *
250      * @param throwable a <code>Throwable</code>
251      * @return an array of Strings describing stack frames.
252      */

253     public static String JavaDoc[] captureStackTrace( final Throwable JavaDoc throwable )
254     {
255         final StringWriter JavaDoc sw = new StringWriter JavaDoc();
256         throwable.printStackTrace( new PrintWriter JavaDoc( sw, true ) );
257         return splitStringInternal( sw.toString(), LINE_SEPARATOR );
258     }
259
260     /**
261      * Splits the string on every token into an array of stack frames.
262      *
263      * @param string the string to split
264      * @param onToken the token to split on
265      * @return the resultant array
266      * @deprecated This is an internal utility method that should not be used
267      */

268     public static String JavaDoc[] splitString( final String JavaDoc string, final String JavaDoc onToken )
269     {
270         return splitStringInternal( string, onToken );
271     }
272
273     /**
274      * Splits the string on every token into an array of stack frames.
275      *
276      * @param string the string to split
277      * @param onToken the token to split on
278      * @return the resultant array
279      */

280     private static String JavaDoc[] splitStringInternal( final String JavaDoc string, final String JavaDoc onToken )
281     {
282         final StringTokenizer JavaDoc tokenizer = new StringTokenizer JavaDoc( string, onToken );
283         final String JavaDoc[] result = new String JavaDoc[ tokenizer.countTokens() ];
284
285         for( int i = 0; i < result.length; i++ )
286         {
287             result[ i ] = tokenizer.nextToken();
288         }
289
290         return result;
291     }
292 }
293
Popular Tags