1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
package Torello.Java;

import static Torello.Java.C.*;

import java.lang.reflect.InvocationTargetException;
import java.util.Arrays;

/**
 * <B><CODE>'Exception Cause Chain'</CODE></B> helps convert exception messages whose
 * <CODE><B>Throwable.cause()</B></CODE> method returns a non-null <CODE>cause</CODE>, thereby
 * unrolling <I>(and printing)</I> this chain of exceptions into a readable <CODE>String</CODE>.
 * 
 * <EMBED CLASS=external-html DATA-FILE-ID=EXCC>
 */
@Torello.JavaDoc.Annotations.StaticFunctional
public class EXCC
{
    private EXCC() { }


    // ********************************************************************************************
    // ********************************************************************************************
    // Print the Cause Chain
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * Convenience Method.
     * <BR />Invokes: {@link #toString(Throwable)}
     * <BR />And-Then: {@link StrIndent#indentTabs(String, int)}
     */
    public static String toString(Throwable t, int indentation)
    { return StrIndent.indentTabs(toString(t), indentation); }

    /**
     * Prints the {@code Exception}-message and {@code Exception}-stack trace to an output
     * {@code String}, and invokes, recursively, this method with any cause-{@code Throwable's}
     * that are present in this {@code Throwable}.
     *
     * @param t Any Java {@code Throwable}.  Java {@code Throwable's} with one or {@code 'cause'}
     * {@code Throwable's} will utilize more fully the printing-features of this class,
     * {@code 'EXCC'} - <I>though any {@code Throwable} will be properly printed</I>.
     * 
     * @return This method doesn't actually print anything to the screen or terminal, it just
     * returns a {@code String} that you may print yourself - <I>or write to a
     * {@code class StringBuilder}, or any variation of text-output you wish.</I>
     */
    public static String toString(Throwable t)
    {
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Initialize the Variables
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        final StackTraceElement[]   steArr          = t.getStackTrace();
        final StringBuilder         sb              = new StringBuilder();
        final Throwable             cause           = t.getCause();
        final Throwable             legacyCause     = legacyCause(t);
        final boolean               hasCause        = (cause != null);
        final boolean               hasLegacyCause  = (legacyCause != null) && (legacyCause != cause);

        String msg          = t.getMessage();
        String localMsg     = t.getLocalizedMessage();
        String legacyMsg    = (hasLegacyCause) ? legacyMsg(t) : null;

        final boolean hasMessage    = (msg != null)         && (msg.length() > 0);
        final boolean hasLocalMsg   = (localMsg != null)    && (localMsg.length() > 0);

        if (hasMessage)     msg         = StrIndent.indent(msg, 1, false, true);
        if (hasLocalMsg)    localMsg    = StrIndent.indent(localMsg, 1, false, true);


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Print the "Top Part" / "Header Part" / Error-Message to the Return-Output StringBuilder
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        sb.append(BRED + "THROWN: " + t.getClass().getCanonicalName() + RESET + "\n");

        if (hasMessage)
        {
            sb.append(BCYAN + "Throwable.getMessage():\n" + RESET + msg + "\n");

            if (hasLocalMsg && (! msg.equals(localMsg)))
                sb.append(BCYAN + "Throwable.getLocalizedMessage():\n" + RESET + localMsg + "\n");
        }

        else if (hasLocalMsg)
            sb.append(BCYAN + "Throwable.getLocalizedMessage():\n" + RESET + localMsg + "\n");

        else
            sb.append(BYELLOW + "No Exception Messages Provided.\n" + RESET);


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Print the Stack-Trace
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        sb.append(BCYAN + "StackTrace:\n" + RESET);

        int temp, maxLN = 0;

        for (StackTraceElement ste : steArr)
            if ((temp = ste.getLineNumber()) > maxLN)
                maxLN = temp;

        final int base10 =
            2 + // 2: colon + space
            ((int) Math.ceil(Math.log10(maxLN)));

        for (int k=0; k < steArr.length; k++) sb.append(
            '\t' + StringParse.rightSpacePad(steArr[k].getLineNumber() + ":", base10) +
            steArr[k].getClassName() + "." +
            steArr[k].getMethodName() + "()\n"
        );


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Build the StringBuilder & Return / Exit
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        return
            sb.toString() +
            (hasCause       ? StrIndent.indentTabs(toString(cause), 1)                      : "") +
            (hasLegacyCause ? (legacyMsg + StrIndent.indentTabs(toString(legacyCause), 1))  : "");
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // Variant: Abbreviated Cause-Chain Printing
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * Convenience Method.
     * <BR />Invokes: {@link #toStringMaxTraces(Throwable, int)}
     * <BR />And-Then: {@link StrIndent#indentTabs(String, int)}
     */
    public static String toStringMaxTraces(Throwable t, int maxNumInvocations, int indentation)
    { return StrIndent.indent(toStringMaxTraces(t, maxNumInvocations), indentation); }

    /**
     * Prints the {@code Exception}-message and {@code Exception}-stack trace to an output
     * {@code String}, and invokes, recursively, this method with any cause-{@code Throwable's}
     * that are present in this {@code Throwable}.
     *
     * @param t Any Java {@code Throwable}.  Java {@code Throwable's} with one or {@code 'cause'}
     * {@code Throwable's} will utilize more fully the printing-features of this class,
     * {@code 'EXCC'} - <I>though any {@code Throwable} will be properly printed</I>.
     * 
     * @param maxNumInvocations Each of the {@code Throwable's} printed shall have, at most,
     * {@code 'maxNumInvocations'} of their Stack-Traces printed into the output {@code String}.
     * 
     * @return This method doesn't actually print anything to the screen or terminal, it just
     * returns a {@code String} that you may print yourself - <I>or write to a
     * {@code class StringBuilder}, or any variation of text-output you wish.</I>
     */
    public static String toStringMaxTraces(Throwable t, int maxNumInvocations)
    {
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Initialize the Variables
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        StackTraceElement[] steArr = t.getStackTrace();

        final StringBuilder sb              = new StringBuilder();
        final Throwable     cause           = t.getCause();
        final Throwable     legacyCause     = legacyCause(t);
        final boolean       hasCause        = (cause != null);
        final boolean       hasLegacyCause  = (legacyCause != null) && (legacyCause != cause);

        String msg          = t.getMessage();
        String localMsg     = t.getLocalizedMessage();
        String legacyMsg    = (hasLegacyCause) ? legacyMsg(t) : null;

        final boolean hasMessage    = (msg != null)         && (msg.length() > 0);
        final boolean hasLocalMsg   = (localMsg != null)    && (localMsg.length() > 0);

        if (hasMessage)     msg         = StrIndent.indent(msg, 1, false, true);
        if (hasLocalMsg)    localMsg    = StrIndent.indent(localMsg, 1, false, true);


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Print the "Top Part" / "Header Part" / Error-Message to the Return-Output StringBuilder
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        sb.append(BRED + "THROWN: " + t.getClass().getCanonicalName() + RESET + "\n");

        if (hasMessage)
        {
            sb.append(BCYAN + "Throwable.getMessage():\n" + RESET + msg + "\n");

            if (hasLocalMsg && (! msg.equals(localMsg)))
                sb.append(BCYAN + "Throwable.getLocalizedMessage():\n" + RESET + localMsg + "\n");
        }

        else if (hasLocalMsg)
            sb.append(BCYAN + "Throwable.getLocalizedMessage():\n" + RESET + localMsg + "\n");

        else
            sb.append(BYELLOW + "No Exception Messages Provided.\n" + RESET);


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Print the Stack-Trace
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        sb.append(BCYAN + "StackTrace:\n" + RESET);

        int temp, maxLN = 0, stTruncated = 0;

        if (steArr.length > maxNumInvocations)
        {
            stTruncated = steArr.length - maxNumInvocations;
            steArr      = Arrays.copyOf(steArr, maxNumInvocations);
        }

        for (StackTraceElement ste : steArr)
            if ((temp = ste.getLineNumber()) > maxLN)
                maxLN = temp;

        final int base10 =
            2 + // 2: colon + space
            ((int) Math.ceil(Math.log10(maxLN)));


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Build the StringBuilder & Return / Exit
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        for (int k=0; k < steArr.length; k++) sb.append(
            '\t' + StringParse.rightSpacePad(steArr[k].getLineNumber() + ":", base10) +
            steArr[k].getClassName() + "." +
            steArr[k].getMethodName() + "()\n"
        );

        if (stTruncated > 0)
            sb.append("\t... and " + stTruncated + " more invocations.\n");


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Build the StringBuilder & Return / Exit
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        return
            sb.toString() +
            (hasCause       ? StrIndent.indentTabs(toString(cause), 1)                      : "") +
            (hasLegacyCause ? (legacyMsg + StrIndent.indentTabs(toString(legacyCause), 1))  : "");
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // Variant: No Stack Trace Printing
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * Convenience Method.
     * <BR />Invokes: {@link #toStringNoST(Throwable)}
     * <BR />And-Then: {@link StrIndent#indentTabs(String, int)}
     */
    public static String toStringNoST(Throwable t, int indentation)
    { return StrIndent.indentTabs(toStringNoST(t), indentation); }

    /**
     * Prints the {@code Exception}-message to an output {@code String}.  Invokes, recursively,
     * this method with any cause-{@code Throwable's} that are present in this {@code Throwable}.
     *
     * <BR /><BR /><DIV CLASS=JDHint>
     * This method differs from {@link #toString(Throwable)}, in that it <B>does not print the
     * {@code StackTrace's} to the output-return {@code String}.</B>
     * </DIV>
     * 
     * @param t Any Java {@code Throwable}.  Java {@code Throwable's} with one or {@code 'cause'}
     * {@code Throwable's} will utilize more fully the printing-features of this class,
     * {@code 'EXCC'} - <I>though any {@code Throwable} will be properly printed</I>.
     * 
     * @return This method doesn't actually print anything to the screen or terminal, it just
     * returns a {@code String} that you may print yourself - <I>or write to a
     * {@code class StorageBuffer,} or any variation of logging you wish.</I>
     */
    public static String toStringNoST(Throwable t)
    {
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Initialize the Variables
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        final StringBuilder sb              = new StringBuilder();
        final Throwable     cause           = t.getCause();
        final Throwable     legacyCause     = legacyCause(t);
        final boolean       hasCause        = (cause != null);
        final boolean       hasLegacyCause  = (legacyCause != null) && (legacyCause != cause);

        String msg          = t.getMessage();
        String localMsg     = t.getLocalizedMessage();
        String legacyMsg    = (hasLegacyCause) ? legacyMsg(t) : null;

        final boolean hasMessage    = (msg != null)         && (msg.length() > 0);
        final boolean hasLocalMsg   = (localMsg != null)    && (localMsg.length() > 0);

        if (hasMessage)     msg         = StrIndent.indent(msg, 1, false, true);
        if (hasLocalMsg)    localMsg    = StrIndent.indent(localMsg, 1, false, true);


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Print the "Top Part" / "Header Part" / Error-Message to the Return-Output StringBuilder
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        sb.append(BRED + "THROWN: " + t.getClass().getCanonicalName() + RESET + "\n");

        if (hasMessage)
        {
            sb.append(BCYAN + "Throwable.getMessage():\n" + RESET + msg + "\n");

            if (hasLocalMsg && (! msg.equals(localMsg)))
                sb.append(BCYAN + "Throwable.getLocalizedMessage():\n" + RESET + localMsg + "\n");
        }

        else if (hasLocalMsg)
            sb.append(BCYAN + "Throwable.getLocalizedMessage():\n" + RESET + localMsg + "\n");

        else
            sb.append(BYELLOW + "No Exception Messages Provided.\n" + RESET);


        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
        // Build the StringBuilder & Return / Exit
        // *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***

        return
            sb.toString() +
            (hasCause
                ? StrIndent.indentTabs(toStringNoST(cause), 1)
                : "") +
            (hasLegacyCause
                ? (legacyMsg + StrIndent.indentTabs(toStringNoST(legacyCause), 1))
                : "");
    }


    // ********************************************************************************************
    // ********************************************************************************************
    // Two Helpers
    // ********************************************************************************************
    // ********************************************************************************************


    /**
     * Helper Method for retrieving exceptions that function in a very similar fashion to a
     * {@code 'cause'} exception.
     * 
     * @param t Any Java Throwable
     * 
     * @return For legacy exception classes, this will return the {@code 'cause'}, using the older
     * method for extracting that cause.
     */
    protected static Throwable legacyCause(final Throwable t)
    {
        if (t instanceof InvocationTargetException)
            return ((InvocationTargetException) t).getTargetException();

        if (t instanceof ExceptionInInitializerError)
            return ((ExceptionInInitializerError) t).getException();

        return null;
    }

    /**
     * Generates a simple descriptive {@code String} whenever there is a cause exception present
     * that has been extracted from one of the older exception classes that can produce such legacy
     * causes.
     * 
     * @param t
     * @return A descriptive {@code String} explaining the legacy cause feature
     */
    protected static String legacyMsg(final Throwable t)
    {
        if (t instanceof InvocationTargetException)
            return "InvocationTargetException.getTargetException():\n";

        if (t instanceof ExceptionInInitializerError)
            return "ExceptionInInitializerError.getException():\n";

        return null;
    }
}