1
2
3
4
5
6
7
8
9
10
11
12
13
14 package ch.qos.logback.core.joran.conditional;
15
16 import java.util.ArrayList;
17 import java.util.List;
18 import java.util.Stack;
19
20 import org.xml.sax.Attributes;
21
22 import ch.qos.logback.core.joran.action.Action;
23 import ch.qos.logback.core.joran.event.InPlayListener;
24 import ch.qos.logback.core.joran.event.SaxEvent;
25 import ch.qos.logback.core.joran.spi.ActionException;
26 import ch.qos.logback.core.joran.spi.InterpretationContext;
27
28 abstract public class ThenOrElseActionBase extends Action {
29
30 Stack<ThenActionState> stateStack = new Stack<ThenActionState>();
31
32 @Override
33 public void begin(InterpretationContext ic, String name, Attributes attributes)
34 throws ActionException {
35
36 if(!weAreActive(ic)) return;
37
38 ThenActionState state = new ThenActionState();
39 if (ic.isListenerListEmpty()) {
40 ic.addInPlayListener(state);
41 state.isRegistered = true;
42 }
43 stateStack.push(state);
44 }
45
46 boolean weAreActive(InterpretationContext ic) {
47 Object o = ic.peekObject();
48 if(!(o instanceof IfAction)) return false;
49 IfAction ifAction = (IfAction) o;
50 return ifAction.isActive();
51 }
52
53 @Override
54 public void end(InterpretationContext ic, String name) throws ActionException {
55 if(!weAreActive(ic)) return;
56
57 ThenActionState state = stateStack.pop();
58 if (state.isRegistered) {
59 ic.removeInPlayListener(state);
60 Object o = ic.peekObject();
61 if (o instanceof IfAction) {
62 IfAction ifAction = (IfAction) o;
63 removeFirstAndLastFromList(state.eventList);
64 registerEventList(ifAction, state.eventList);
65 } else {
66 throw new IllegalStateException("Missing IfAction on top of stack");
67 }
68 }
69 }
70
71 abstract void registerEventList(IfAction ifAction, List<SaxEvent> eventList);
72
73 void removeFirstAndLastFromList(List<SaxEvent> eventList) {
74 eventList.remove(0);
75 eventList.remove(eventList.size() - 1);
76 }
77
78 }
79
80 class ThenActionState implements InPlayListener {
81
82 List<SaxEvent> eventList = new ArrayList<SaxEvent>();
83 boolean isRegistered = false;
84
85 public void inPlay(SaxEvent event) {
86 eventList.add(event);
87 }
88 }