1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.logging.log4j.core.util;
18
19 import java.io.IOException;
20 import java.io.InterruptedIOException;
21 import java.io.LineNumberReader;
22 import java.io.PrintWriter;
23 import java.io.StringReader;
24 import java.io.StringWriter;
25 import java.lang.reflect.InvocationTargetException;
26 import java.lang.reflect.Method;
27 import java.util.ArrayList;
28 import java.util.List;
29
30 import org.apache.logging.log4j.status.StatusLogger;
31
32
33
34
35 public final class Throwables {
36
37 private static final Method ADD_SUPPRESSED;
38
39 private static final Method GET_SUPPRESSED;
40
41 static {
42 Method getSuppressed = null, addSuppressed = null;
43 final Method[] methods = Throwable.class.getMethods();
44 for (final Method method : methods) {
45 if (method.getName().equals("getSuppressed")) {
46 getSuppressed = method;
47 } else if (method.getName().equals("addSuppressed")) {
48 addSuppressed = method;
49 }
50 }
51 GET_SUPPRESSED = getSuppressed;
52 ADD_SUPPRESSED = addSuppressed;
53 }
54
55
56
57
58
59
60
61
62
63
64 @Deprecated
65 public static void addSuppressed(final Throwable throwable, final Throwable suppressedThrowable) {
66 if (ADD_SUPPRESSED != null) {
67 try {
68 ADD_SUPPRESSED.invoke(throwable, suppressedThrowable);
69 } catch (final IllegalAccessException e) {
70
71 StatusLogger.getLogger().error(e);
72 } catch (final IllegalArgumentException e) {
73
74 StatusLogger.getLogger().error(e);
75 } catch (final InvocationTargetException e) {
76
77 StatusLogger.getLogger().error(e);
78 }
79 }
80
81 }
82
83
84
85
86
87
88
89
90
91
92 @Deprecated
93 public static Throwable[] getSuppressed(final Throwable throwable) {
94 if (GET_SUPPRESSED != null) {
95 try {
96 return (Throwable[]) GET_SUPPRESSED.invoke(throwable);
97 } catch (final Exception e) {
98
99 StatusLogger.getLogger().error(e);
100 return null;
101 }
102 }
103 return null;
104 }
105
106
107
108
109
110
111 public static boolean isGetSuppressedAvailable() {
112 return GET_SUPPRESSED != null;
113 }
114
115
116
117
118
119
120
121 public static List<String> toStringList(final Throwable throwable) {
122 final StringWriter sw = new StringWriter();
123 final PrintWriter pw = new PrintWriter(sw);
124 try {
125 throwable.printStackTrace(pw);
126 } catch (final RuntimeException ex) {
127
128 }
129 pw.flush();
130 final List<String> lines = new ArrayList<String>();
131 final LineNumberReader reader = new LineNumberReader(new StringReader(sw.toString()));
132 try {
133 String line = reader.readLine();
134 while (line != null) {
135 lines.add(line);
136 line = reader.readLine();
137 }
138 } catch (final IOException ex) {
139 if (ex instanceof InterruptedIOException) {
140 Thread.currentThread().interrupt();
141 }
142 lines.add(ex.toString());
143 } finally {
144 Closer.closeSilently(reader);
145 }
146 return lines;
147 }
148
149 private Throwables() {
150 }
151
152 }