1 16 package org.apache.commons.chain.impl; 17 18 19 import java.util.Collection ; 20 import java.util.Iterator ; 21 import org.apache.commons.chain.Chain; 22 import org.apache.commons.chain.Command; 23 import org.apache.commons.chain.Context; 24 import org.apache.commons.chain.Filter; 25 26 27 33 34 public class ChainBase implements Chain { 35 36 37 39 40 43 public ChainBase() { 44 45 } 46 47 48 57 public ChainBase(Command command) { 58 59 addCommand(command); 60 61 } 62 63 64 74 public ChainBase(Command[] commands) { 75 76 if (commands == null) { 77 throw new IllegalArgumentException (); 78 } 79 for (int i = 0; i < commands.length; i++) { 80 addCommand(commands[i]); 81 } 82 83 } 84 85 86 96 public ChainBase(Collection commands) { 97 98 if (commands == null) { 99 throw new IllegalArgumentException (); 100 } 101 Iterator elements = commands.iterator(); 102 while (elements.hasNext()) { 103 addCommand((Command) elements.next()); 104 } 105 106 } 107 108 109 111 112 117 protected Command[] commands = new Command[0]; 118 119 120 124 protected boolean frozen = false; 125 126 127 129 130 public void addCommand(Command command) { 132 133 if (command == null) { 134 throw new IllegalArgumentException (); 135 } 136 if (frozen) { 137 throw new IllegalStateException (); 138 } 139 Command[] results = new Command[commands.length + 1]; 140 System.arraycopy(commands, 0, results, 0, commands.length); 141 results[commands.length] = command; 142 commands = results; 143 144 } 145 146 147 public boolean execute(Context context) throws Exception { 149 150 if (context == null) { 152 throw new IllegalArgumentException (); 153 } 154 155 frozen = true; 157 158 boolean saveResult = false; 161 Exception saveException = null; 162 int i = 0; 163 int n = commands.length;; 164 for (i = 0; i < n; i++) { 165 try { 166 saveResult = commands[i].execute(context); 167 if (saveResult) { 168 break; 169 } 170 } catch (Exception e) { 171 saveException = e; 172 break; 173 } 174 } 175 176 if (i >= n) { i--; 179 } 180 boolean handled = false; 181 boolean result = false; 182 for (int j = i; j >= 0; j--) { 183 if (commands[j] instanceof Filter) { 184 try { 185 result = 186 ((Filter) commands[j]).postprocess(context, 187 saveException); 188 if (result) { 189 handled = true; 190 } 191 } catch (Exception e) { 192 ; } 194 } 195 } 196 197 if ((saveException != null) && !handled) { 199 throw saveException; 200 } else { 201 return (saveResult); 202 } 203 204 } 205 206 207 209 210 215 Command[] getCommands() { 216 217 return (commands); 218 219 } 220 221 222 } 223 | Popular Tags |