-
Notifications
You must be signed in to change notification settings - Fork 0
/
ExceptionContext.java
232 lines (204 loc) · 8.33 KB
/
ExceptionContext.java
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
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.github.leoniedermeier.utils.excecption;
import static java.util.stream.Collectors.toSet;
import java.io.PrintWriter;
import java.io.Serializable;
import java.io.StringWriter;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Stream;
/**
* Allows the storage and retrieval of contextual information based on
* label-value pairs for exceptions.
*
* @param <T> The {@link ExceptionContext} type subclass
*/
public interface ExceptionContext<T extends ExceptionContext<T>> {
/**
* A label-value pair.
*/
class Entry implements Serializable {
@SuppressWarnings("squid:S4926")
private static final long serialVersionUID = -3878722290376314455L;
private String label;
// special handling in writeReplace method
@SuppressWarnings("squid:S1948")
private Object value;
public Entry(String label, Object value) {
super();
this.label = label;
this.value = value;
}
public String getLabel() {
return label;
}
public Object getValue() {
return value;
}
private Object writeReplace() {
if (value instanceof Serializable) {
return this;
} else {
try {
return new Entry(label, ">> Stringified Value Object: <<::" + value);
} catch (Exception e) {
return new Entry(label, ">> Value Object not serializeable <<");
}
}
}
}
/**
* Adds a contextual label-value pair into this context.
* <p>
* The pair will be added to the context, independently of an already existing
* pair with the same label.
* </p>
*
* @param label The label of the item to add, {@code null} not recommended
* @param value The value of item to add, may be {@code null}
* @return {@code this}, for method chaining, not {@code null}
*/
@SuppressWarnings("unchecked")
default T addContextValue(final String label, final Object value) {
getContextEntries().add(new Entry(label, value));
return (T) this;
}
/**
* Retrieves the first available contextual data value associated with the
* label.
*
* @param label The label to get the contextual value for, may be {@code null}
* @return The first contextual value associated with the label.
*/
default Optional<Object> findFirstContextValue(final String label) {
return findFirstContextValue(label, Object.class);
}
/**
* Retrieves the first available contextual data value associated with the label
* and which are instances of the given class.
*
* @param label The label to get the contextual value for, may be
* {@code null}
* @param requiredClass The required class of the values.
* @return The first contextual value associated with the label and class.
*/
default <R> Optional<R> findFirstContextValue(final String label, Class<R> requiredClass) {
return getContextValues(label, requiredClass).findFirst();
}
/**
* Retrieves the last available contextual data value associated with the label.
*
* @param label The label to get the contextual value for, may be {@code null}
* @return The first contextual value associated with the label.
*/
default Optional<Object> findLastContextValue(final String label) {
return getContextValues(label, Object.class).reduce((first, second) -> second);
}
/**
* Retrieves the last available contextual data value associated with the label
* and which are instances of the given class.
*
* @param label The label to get the contextual value for, may be
* {@code null}
* @param requiredClass The required class of the values.
* @return the first contextual value associated with the label and class.
*/
default <R> Optional<R> findLastContextValue(final String label, Class<R> requiredClass) {
return getContextValues(label, requiredClass).reduce((first, second) -> second);
}
/**
* Retrieves the full list of {@link Entry}s defined in the contextual data.
*
* @return The list of {@link Entry}s, not {@code null}
*/
List<Entry> getContextEntries();
/**
* Retrieves the full set of labels defined in the contextual data.
*
* @return the set of labels, not {@code null}
*/
default Set<String> getContextLabels() {
return getContextEntries().stream().map(Entry::getLabel).collect(toSet());
}
/**
* Retrieves all the contextual data values associated with the label.
*
* @param label the label to get the contextual values for, may be {@code null}
* @return the contextual values associated with the label, never {@code null}
*/
default Stream<Object> getContextValues(final String label) {
return getContextValues(label, Object.class);
}
/**
* Retrieves all the contextual data values associated with the label and which
* are instances of the given class.
*
* @param label The label to get the contextual values for, may be
* {@code null}
* @param requiredClass The required class of the values.
* @return the contextual values associated with the label, never {@code null}
*/
default <R> Stream<R> getContextValues(final String label, Class<R> requiredClass) {
return getContextEntries().stream().filter(e -> Objects.equals(label, e.getLabel())).map(Entry::getValue)
.filter(requiredClass::isInstance).map(requiredClass::cast);
}
/**
* Gets the contextualized error message based on a base message. This will add
* the context label-value pairs to the message.
*
* information appended
*
* @return the exception message <b>with</b> context information appended, not
* {@code null}
*/
default String getFormattedExceptionMessage() {
List<Entry> contextEntries = getContextEntries();
if (contextEntries.isEmpty()) {
return "";
}
final StringBuilder buffer = new StringBuilder(256);
buffer.append("Exception Context:\n");
for (final Entry entry : contextEntries) {
buffer.append(" ");
buffer.append(entry.getLabel());
buffer.append(": ");
try {
buffer.append(entry.getValue());
} catch (final Exception e) {
buffer.append("Exception thrown on toString(): ");
final StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw, true));
buffer.append(sw.getBuffer());
}
buffer.append('\n');
}
buffer.append("---------------------------------");
return buffer.toString();
}
default String getFormattedExceptionMessage(final String baseMessage) {
final StringBuilder buffer = new StringBuilder(256);
if (baseMessage != null) {
buffer.append(baseMessage);
}
buffer.append('\n');
buffer.append(getFormattedExceptionMessage());
return buffer.toString();
}
}