forked from jooby-project/jooby
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCompletionListeners.java
More file actions
64 lines (60 loc) · 1.54 KB
/
CompletionListeners.java
File metadata and controls
64 lines (60 loc) · 1.54 KB
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
/**
* Jooby https://jooby.io
* Apache License Version 2.0 https://jooby.io/LICENSE.txt
* Copyright 2014 Edgar Espina
*/
package io.jooby;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;
/**
* Utility class that group one or more completion listeners and execute them in reverse order.
*
* @author edgar
* @since 2.5.2
*/
public class CompletionListeners {
private List<Route.Complete> listeners;
/**
* Add a listener.
*
* @param listener Listener.
*/
public void addListener(@Nonnull Route.Complete listener) {
if (listeners == null) {
listeners = new ArrayList<>();
}
listeners.add(listener);
}
/**
* Execute all listeners.
*
* @param ctx Listeners.
*/
public void run(@Nonnull Context ctx) {
if (listeners != null) {
Throwable cause = null;
for (int i = listeners.size() - 1; i >= 0; i--) {
try {
listeners.get(i).apply(ctx);
} catch (Throwable x) {
if (cause == null) {
cause = x;
} else {
cause.addSuppressed(x);
}
}
}
if (cause != null) {
ctx.getRouter().getLog()
.error("Completion listener(s) resulted in exception(s): {} {}", ctx.getMethod(),
ctx.getRequestPath(), cause);
Stream.concat(Stream.of(cause), Stream.of(cause.getSuppressed()))
.filter(SneakyThrows::isFatal)
.findFirst()
.ifPresent(SneakyThrows::propagate);
}
}
}
}