1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17 package org.apache.commons.scxml2.model;
18
19 import java.lang.reflect.Array;
20 import java.util.ArrayList;
21 import java.util.List;
22
23 import org.apache.commons.scxml2.ActionExecutionContext;
24 import org.apache.commons.scxml2.Context;
25 import org.apache.commons.scxml2.Evaluator;
26 import org.apache.commons.scxml2.SCXMLExpressionException;
27
28
29
30
31
32
33 public class Foreach extends Action implements ActionsContainer {
34
35
36
37
38 private static final long serialVersionUID = 1L;
39
40 private String array;
41 private String item;
42 private String index;
43
44
45
46
47
48 private List<Action> actions;
49
50 public Foreach() {
51 super();
52 this.actions = new ArrayList<Action>();
53 }
54
55 @Override
56 public final String getContainerElementName() {
57 return ELEM_FOREACH;
58 }
59
60 @Override
61 public final List<Action> getActions() {
62 return actions;
63 }
64
65 @Override
66 public final void addAction(final Action action) {
67 if (action != null) {
68 this.actions.add(action);
69 }
70 }
71
72 public String getArray() {
73 return array;
74 }
75
76 public void setArray(final String array) {
77 this.array = array;
78 }
79
80 public String getItem() {
81 return item;
82 }
83
84 public void setItem(final String item) {
85 this.item = item;
86 }
87
88 public String getIndex() {
89 return index;
90 }
91
92 public void setIndex(final String index) {
93 this.index = index;
94 }
95
96
97
98
99 @Override
100 public void execute(ActionExecutionContext exctx) throws ModelException, SCXMLExpressionException {
101 Context ctx = exctx.getContext(getParentEnterableState());
102 Evaluator eval = exctx.getEvaluator();
103 ctx.setLocal(getNamespacesKey(), getNamespaces());
104 try {
105 Object arrayObject = eval.eval(ctx,array);
106 if (arrayObject != null && (arrayObject instanceof Iterable || arrayObject.getClass().isArray())) {
107 if (arrayObject.getClass().isArray()) {
108 for (int currentIndex = 0, size = Array.getLength(arrayObject); currentIndex < size; currentIndex++) {
109 ctx.setLocal(item, Array.get(arrayObject, currentIndex));
110 if (index != null) {
111 ctx.setLocal(index, currentIndex);
112 }
113
114 for (Action aa : actions) {
115 aa.execute(exctx);
116 }
117 }
118 }
119 else {
120
121
122
123
124 ArrayList<Object> arrayList = new ArrayList<Object>();
125 for (Object value: (Iterable)arrayObject) {
126 arrayList.add(value);
127 }
128 int currentIndex = 0;
129 for (Object value : arrayList) {
130 ctx.setLocal(item, value);
131 if (index != null) {
132 ctx.setLocal(index, currentIndex);
133 }
134
135 for (Action aa : actions) {
136 aa.execute(exctx);
137 }
138 currentIndex++;
139 }
140 }
141 }
142
143 }
144 finally {
145 ctx.setLocal(getNamespacesKey(), null);
146 }
147 }
148 }