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 package info.magnolia.commands.chain;
35
36 import java.util.Collection;
37 import java.util.Collections;
38 import java.util.LinkedList;
39 import java.util.List;
40
41
42
43
44
45
46 public class ChainBase implements Chain {
47
48 protected List<Command> commands = new LinkedList<Command>();
49
50 protected boolean frozen = false;
51
52 public ChainBase() {
53 }
54
55 public ChainBase(Command command) {
56 addCommand(command);
57 }
58
59 public ChainBase(Command... commands) {
60 for (Command command : commands) {
61 addCommand(command);
62 }
63 }
64
65 public ChainBase(Collection<Command> commands) {
66 this(commands.toArray(new Command[0]));
67 }
68
69 @Override
70 public void addCommand(Command command) {
71 if (command == null) {
72 throw new IllegalArgumentException();
73 }
74 if (frozen) {
75 throw new IllegalStateException();
76 }
77 commands.add(command);
78 }
79
80 @Override
81 public boolean execute(Context context) throws Exception {
82
83 if (context == null) {
84 throw new IllegalArgumentException();
85 }
86
87 frozen = true;
88
89
90 boolean saveResult = false;
91 Exception saveException = null;
92 int i = 0;
93 int n = commands.size();
94 for (i = 0; i < n; i++) {
95 try {
96 saveResult = commands.get(i).execute(context);
97 if (saveResult) {
98 break;
99 }
100 } catch (Exception e) {
101 saveException = e;
102 break;
103 }
104 }
105
106 if (i >= n) {
107 i--;
108 }
109 boolean handled = false;
110 boolean result = false;
111 for (int j = i; j >= 0; j--) {
112 if (commands.get(j) instanceof Filter) {
113 try {
114 result = ((Filter) commands.get(j)).postprocess(context, saveException);
115 if (result) {
116 handled = true;
117 }
118 } catch (Exception e) {
119
120 }
121 }
122 }
123
124 if ((saveException != null) && !handled) {
125 throw saveException;
126 }
127 return (saveResult);
128 }
129
130
131
132
133 public List<Command> getCommands() {
134 return Collections.unmodifiableList(commands);
135 }
136
137 @Override
138 public Chain copy(Command command) {
139 ChainBase master = (ChainBase) command;
140 ChainBase copy = new ChainBase();
141 for (Command c : master.commands) {
142 copy.addCommand(c.copy(c));
143 }
144 return copy;
145 }
146
147 }