01: package org.jbpm.command;
02:
03: import java.lang.reflect.Field;
04: import java.util.ArrayList;
05: import java.util.Iterator;
06: import java.util.List;
07:
08: import org.jbpm.JbpmContext;
09: import org.jbpm.JbpmException;
10:
11: public class CompositeCommand implements Command {
12:
13: private static final long serialVersionUID = 1L;
14:
15: List commands = null;
16:
17: public CompositeCommand(List commands) {
18: this .commands = commands;
19: }
20:
21: public Object execute(JbpmContext jbpmContext) throws Exception {
22: List results = null;
23: if (commands != null) {
24: Object lastResult = null;
25: results = new ArrayList(commands.size());
26: Iterator iter = commands.iterator();
27: while (iter.hasNext()) {
28: Command command = (Command) iter.next();
29: if (lastResult != null) {
30: tryToInject(lastResult, command);
31: }
32: lastResult = command.execute(jbpmContext);
33: results.add(lastResult);
34: }
35: }
36: return results;
37: }
38:
39: protected void tryToInject(Object lastResult, Command command) {
40: Field field = findField(lastResult.getClass());
41: if (field != null) {
42: field.setAccessible(true);
43: try {
44: field.set(command, lastResult);
45: } catch (Exception e) {
46: throw new JbpmException(
47: "couldn't propagate composite command context",
48: e);
49: }
50: }
51: }
52:
53: protected Field findField(Class clazz) {
54: Field field = null;
55: int i = 0;
56: Field[] fields = clazz.getDeclaredFields();
57: while ((i < fields.length) && (field == null)) {
58: Field candidate = fields[i];
59: if ((candidate.getType().isAssignableFrom(clazz))
60: && (candidate.getName().startsWith("previous"))) {
61: field = candidate;
62: }
63: i++;
64: }
65: return field;
66: }
67: }
|