Debian Codegraph @

src/main/java/net/sf/antcontrib/logic/ForTask.java

raw symbols SCIP
1 /*
2 * Copyright (c) 2003-2005 Ant-Contrib project. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16 package net.sf.antcontrib.logic;
17
18 import java.io.File;
19 import java.lang.reflect.Method;
20 import java.util.ArrayList;
21 import java.util.Collection;
22 import java.util.Iterator;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.StringTokenizer;
26
27 import org.apache.tools.ant.BuildException;
28 import org.apache.tools.ant.Project;
29 import org.apache.tools.ant.Task;
30 import org.apache.tools.ant.taskdefs.MacroDef;
31 import org.apache.tools.ant.taskdefs.MacroInstance;
32 import org.apache.tools.ant.taskdefs.Parallel;
33 import org.apache.tools.ant.types.DirSet;
34 import org.apache.tools.ant.types.FileSet;
35 import org.apache.tools.ant.types.Path;
36
37 /***
38 * Task definition for the for task. This is based on
39 * the foreach task but takes a sequential element
40 * instead of a target and only works for ant >= 1.6Beta3
41 * @author Peter Reilly
42 */
43 public class ForTask extends Task {
44
45 private String list;
46 private String param;
47 private String delimiter = ",";
48 private Path currPath;
49 private boolean trim;
50 private boolean keepgoing = false;
51 private MacroDef macroDef;
52 private List hasIterators = new ArrayList();
53 private boolean parallel = false;
54 private Integer threadCount;
55 private Parallel parallelTasks;
56 private int begin = 0;
57 private Integer end = null;
58 private int step = 1;
59
60 private int taskCount = 0;
61 private int errorCount = 0;
62
63 /**
64 * Creates a new <code>For</code> instance.
65 */
66 public ForTask() {
67 }
68
69 /**
70 * Attribute whether to execute the loop in parallel or in sequence.
71 * @param parallel if true execute the tasks in parallel. Default is false.
72 */
73 public void setParallel(boolean parallel) {
74 this.parallel = parallel;
75 }
76
77 /***
78 * Set the maximum amount of threads we're going to allow
79 * to execute in parallel
80 * @param threadCount the number of threads to use
81 */
82 public void setThreadCount(int threadCount) {
83 if (threadCount < 1) {
84 throw new BuildException("Illegal value for threadCount " + threadCount
85 + " it should be > 0");
86 }
87 this.threadCount = new Integer(threadCount);
88 }
89
90 /**
91 * Set the trim attribute.
92 *
93 * @param trim if true, trim the value for each iterator.
94 */
95 public void setTrim(boolean trim) {
96 this.trim = trim;
97 }
98
99 /**
100 * Set the keepgoing attribute, indicating whether we
101 * should stop on errors or continue heedlessly onward.
102 *
103 * @param keepgoing a boolean, if <code>true</code> then we act in
104 * the keepgoing manner described.
105 */
106 public void setKeepgoing(boolean keepgoing) {
107 this.keepgoing = keepgoing;
108 }
109
110 /**
111 * Set the list attribute.
112 *
113 * @param list a list of delimiter separated tokens.
114 */
115 public void setList(String list) {
116 this.list = list;
117 }
118
119 /**
120 * Set the delimiter attribute.
121 *
122 * @param delimiter the delimiter used to separate the tokens in
123 * the list attribute. The default is ",".
124 */
125 public void setDelimiter(String delimiter) {
126 this.delimiter = delimiter;
127 }
128
129 /**
130 * Set the param attribute.
131 * This is the name of the macrodef attribute that
132 * gets set for each iterator of the sequential element.
133 *
134 * @param param the name of the macrodef attribute.
135 */
136 public void setParam(String param) {
137 this.param = param;
138 }
139
140 private Path getOrCreatePath() {
141 if (currPath == null) {
142 currPath = new Path(getProject());
143 }
144 return currPath;
145 }
146
147 /**
148 * This is a path that can be used instread of the list
149 * attribute to interate over. If this is set, each
150 * path element in the path is used for an interator of the
151 * sequential element.
152 *
153 * @param path the path to be set by the ant script.
154 */
155 public void addConfigured(Path path) {
156 getOrCreatePath().append(path);
157 }
158
159 /**
160 * This is a path that can be used instread of the list
161 * attribute to interate over. If this is set, each
162 * path element in the path is used for an interator of the
163 * sequential element.
164 *
165 * @param path the path to be set by the ant script.
166 */
167 public void addConfiguredPath(Path path) {
168 addConfigured(path);
169 }
170
171 /**
172 * @return a MacroDef#NestedSequential object to be configured
173 */
174 public Object createSequential() {
175 macroDef = new MacroDef();
176 macroDef.setProject(getProject());
177 return macroDef.createSequential();
178 }
179
180 /**
181 * Set begin attribute.
182 * @param begin the value to use.
183 */
184 public void setBegin(int begin) {
185 this.begin = begin;
186 }
187
188 /**
189 * Set end attribute.
190 * @param end the value to use.
191 */
192 public void setEnd(Integer end) {
193 this.end = end;
194 }
195
196 /**
197 * Set step attribute.
198 *
199 */
200 public void setStep(int step) {
201 this.step = step;
202 }
203
204
205 /**
206 * Run the for task.
207 * This checks the attributes and nested elements, and
208 * if there are ok, it calls doTheTasks()
209 * which constructes a macrodef task and a
210 * for each interation a macrodef instance.
211 */
212 public void execute() {
213 if (parallel) {
214 parallelTasks = (Parallel) getProject().createTask("parallel");
215 if (threadCount != null) {
216 parallelTasks.setThreadCount(threadCount.intValue());
217 }
218 }
219 if (list == null && currPath == null && hasIterators.size() == 0
220 && end == null) {
221 throw new BuildException(
222 "You must have a list or path or sequence to iterate through");
223 }
224 if (param == null) {
225 throw new BuildException(
226 "You must supply a property name to set on"
227 + " each iteration in param");
228 }
229 if (macroDef == null) {
230 throw new BuildException(
231 "You must supply an embedded sequential "
232 + "to perform");
233 }
234 if (end != null) {
235 int iEnd = end.intValue();
236 if (step == 0) {
237 throw new BuildException("step cannot be 0");
238 } else if (iEnd > begin && step < 0) {
239 throw new BuildException("end > begin, step needs to be > 0");
240 } else if (iEnd <= begin && step > 0) {
241 throw new BuildException("end <= begin, step needs to be < 0");
242 }
243 }
244 doTheTasks();
245 if (parallel) {
246 parallelTasks.perform();
247 }
248 }
249
250
251 private void doSequentialIteration(String val) {
252 MacroInstance instance = new MacroInstance();
253 instance.setProject(getProject());
254 instance.setOwningTarget(getOwningTarget());
255 instance.setMacroDef(macroDef);
256 instance.setDynamicAttribute(param.toLowerCase(),
257 val);
258 if (!parallel) {
259 instance.execute();
260 } else {
261 parallelTasks.addTask(instance);
262 }
263 }
264
265 private void doToken(String tok) {
266 try {
267 taskCount++;
268 doSequentialIteration(tok);
269 } catch (BuildException bx) {
270 if (keepgoing) {
271 log(tok + ": " + bx.getMessage(), Project.MSG_ERR);
272 errorCount++;
273 } else {
274 throw bx;
275 }
276 }
277 }
278
279 private void doTheTasks() {
280 errorCount = 0;
281 taskCount = 0;
282
283 // Create a macro attribute
284 if (macroDef.getAttributes().isEmpty()) {
285 MacroDef.Attribute attribute = new MacroDef.Attribute();
286 attribute.setName(param);
287 macroDef.addConfiguredAttribute(attribute);
288 }
289
290 // Take Care of the list attribute
291 if (list != null) {
292 StringTokenizer st = new StringTokenizer(list, delimiter);
293
294 while (st.hasMoreTokens()) {
295 String tok = st.nextToken();
296 if (trim) {
297 tok = tok.trim();
298 }
299 doToken(tok);
300 }
301 }
302
303 // Take care of the begin/end/step attributes
304 if (end != null) {
305 int iEnd = end.intValue();
306 if (step > 0) {
307 for (int i = begin; i < (iEnd + 1); i = i + step) {
308 doToken("" + i);
309 }
310 } else {
311 for (int i = begin; i > (iEnd - 1); i = i + step) {
312 doToken("" + i);
313 }
314 }
315 }
316
317 // Take Care of the path element
318 String[] pathElements = new String[0];
319 if (currPath != null) {
320 pathElements = currPath.list();
321 }
322 for (int i = 0; i < pathElements.length; i++) {
323 File nextFile = new File(pathElements[i]);
324 doToken(nextFile.getAbsolutePath());
325 }
326
327 // Take care of iterators
328 for (Iterator i = hasIterators.iterator(); i.hasNext();) {
329 Iterator it = ((HasIterator) i.next()).iterator();
330 while (it.hasNext()) {
331 doToken(it.next().toString());
332 }
333 }
334 if (keepgoing && (errorCount != 0)) {
335 throw new BuildException(
336 "Keepgoing execution: " + errorCount
337 + " of " + taskCount + " iterations failed.");
338 }
339 }
340
341 /**
342 * Add a Map, iterate over the values
343 *
344 * @param map a Map object - iterate over the values.
345 */
346 public void add(Map map) {
347 hasIterators.add(new MapIterator(map));
348 }
349
350 /**
351 * Add a fileset to be iterated over.
352 *
353 * @param fileset a <code>FileSet</code> value
354 */
355 public void add(FileSet fileset) {
356 getOrCreatePath().addFileset(fileset);
357 }
358
359 /**
360 * Add a fileset to be iterated over.
361 *
362 * @param fileset a <code>FileSet</code> value
363 */
364 public void addFileSet(FileSet fileset) {
365 add(fileset);
366 }
367
368 /**
369 * Add a dirset to be iterated over.
370 *
371 * @param dirset a <code>DirSet</code> value
372 */
373 public void add(DirSet dirset) {
374 getOrCreatePath().addDirset(dirset);
375 }
376
377 /**
378 * Add a dirset to be iterated over.
379 *
380 * @param dirset a <code>DirSet</code> value
381 */
382 public void addDirSet(DirSet dirset) {
383 add(dirset);
384 }
385
386 /**
387 * Add a collection that can be iterated over.
388 *
389 * @param collection a <code>Collection</code> value.
390 */
391 public void add(Collection collection) {
392 hasIterators.add(new ReflectIterator(collection));
393 }
394
395 /**
396 * Add an iterator to be iterated over.
397 *
398 * @param iterator an <code>Iterator</code> value
399 */
400 public void add(Iterator iterator) {
401 hasIterators.add(new IteratorIterator(iterator));
402 }
403
404 /**
405 * Add an object that has an Iterator iterator() method
406 * that can be iterated over.
407 *
408 * @param obj An object that can be iterated over.
409 */
410 public void add(Object obj) {
411 hasIterators.add(new ReflectIterator(obj));
412 }
413
414 /**
415 * Interface for the objects in the iterator collection.
416 */
417 private interface HasIterator {
418 Iterator iterator();
419 }
420
421 private static class IteratorIterator implements HasIterator {
422 private Iterator iterator;
423 public IteratorIterator(Iterator iterator) {
424 this.iterator = iterator;
425 }
426 public Iterator iterator() {
427 return this.iterator;
428 }
429 }
430
431 private static class MapIterator implements HasIterator {
432 private Map map;
433 public MapIterator(Map map) {
434 this.map = map;
435 }
436 public Iterator iterator() {
437 return map.values().iterator();
438 }
439 }
440
441 private static class ReflectIterator implements HasIterator {
442 private Object obj;
443 private Method method;
444 public ReflectIterator(Object obj) {
445 this.obj = obj;
446 try {
447 method = obj.getClass().getMethod(
448 "iterator", new Class[] {});
449 } catch (Throwable t) {
450 throw new BuildException(
451 "Invalid type " + obj.getClass() + " used in For task, it does"
452 + " not have a public iterator method");
453 }
454 }
455
456 public Iterator iterator() {
457 try {
458 return (Iterator) method.invoke(obj, new Object[] {});
459 } catch (Throwable t) {
460 throw new BuildException(t);
461 }
462 }
463 }
464 }