Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * Copyright (c) 2001-2004 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.util.Enumeration;
20 import java.util.StringTokenizer;
21 import java.util.Vector;
22
23 import org.apache.tools.ant.BuildException;
24 import org.apache.tools.ant.Project;
25 import org.apache.tools.ant.Task;
26 import org.apache.tools.ant.TaskContainer;
27 import org.apache.tools.ant.taskdefs.Ant;
28 import org.apache.tools.ant.taskdefs.CallTarget;
29 import org.apache.tools.ant.taskdefs.Property;
30 import org.apache.tools.ant.types.FileSet;
31 import org.apache.tools.ant.types.Mapper;
32 import org.apache.tools.ant.types.Path;
33 import org.apache.tools.ant.util.FileNameMapper;
34
35 import net.sf.antcontrib.util.ThreadPool;
36 import net.sf.antcontrib.util.ThreadPoolThread;
37
38 /***
39 * Task definition for the foreach task. The foreach task iterates
40 * over a list, a list of filesets, or both.
41 *
42 * <pre>
43 *
44 * Usage:
45 *
46 * Task declaration in the project:
47 * <code>
48 * &lt;taskdef name="foreach" classname="net.sf.antcontrib.logic.ForEach" /&gt;
49 * </code>
50 *
51 * Call Syntax:
52 * <code>
53 * &lt;foreach list="values" target="targ" param="name"
54 * [parallel="true|false"]
55 * [delimiter="delim"] /&gt;
56 * </code>
57 *
58 * Attributes:
59 * list --> The list of values to process, with the delimiter character,
60 * indicated by the "delim" attribute, separating each value
61 * target --> The target to call for each token, passing the token as the
62 * parameter with the name indicated by the "param" attribute
63 * param --> The name of the parameter to pass the tokens in as to the
64 * target
65 * delimiter --> The delimiter string that separates the values in the "list"
66 * parameter. The default is ","
67 * parallel --> Should all targets execute in parallel. The default is false.
68 * trim --> Should we trim the list item before calling the target?
69 *
70 * </pre>
71 * @author <a href="mailto:[email protected]">Matthew Inger</a>
72 */
73 public class ForEach extends Task
74 {
75 private String list;
76 private String param;
77 private String delimiter;
78 private String target;
79 private boolean inheritAll;
80 private boolean inheritRefs;
81 private Vector params;
82 private Vector references;
83 private Path currPath;
84 private boolean parallel;
85 private boolean trim;
86 private int maxThreads;
87 private Mapper mapper;
88
89 /***
90 * Default Constructor
91 */
92 public ForEach()
93 {
94 super();
95 this.list = null;
96 this.param = null;
97 this.delimiter = ",";
98 this.target = null;
99 this.inheritAll = false;
100 this.inheritRefs = false;
101 this.params = new Vector();
102 this.references = new Vector();
103 this.parallel = false;
104 this.maxThreads = 5;
105 }
106
107 private void executeParallel(Vector tasks)
108 {
109 ThreadPool pool = new ThreadPool(maxThreads);
110 Enumeration e = tasks.elements();
111 Runnable r = null;
112 Vector threads = new Vector();
113
114 // start each task in it's own thread, using the
115 // pool to ensure that we don't exceed the maximum
116 // amount of threads
117 while (e.hasMoreElements())
118 {
119 // Create the Runnable object
120 final Task task = (Task)e.nextElement();
121 r = new Runnable()
122 {
123 public void run()
124 {
125 task.execute();
126 }
127 };
128
129 // Get a thread, and start the task.
130 // If there is no thread available, this will
131 // block until one becomes available
132 try
133 {
134 ThreadPoolThread tpt = pool.borrowThread();
135 tpt.setRunnable(r);
136 tpt.start();
137 threads.addElement(tpt);
138 }
139 catch (Exception ex)
140 {
141 throw new BuildException(ex);
142 }
143
144 }
145
146 // Wait for all threads to finish before we
147 // are allowed to return.
148 Enumeration te = threads.elements();
149 Thread t= null;
150 while (te.hasMoreElements())
151 {
152 t = (Thread)te.nextElement();
153 if (t.isAlive())
154 {
155 try
156 {
157 t.join();
158 }
159 catch (InterruptedException ex)
160 {
161 throw new BuildException(ex);
162 }
163 }
164 }
165 }
166
167 private void executeSequential(Vector tasks)
168 {
169 TaskContainer tc = (TaskContainer) getProject().createTask("sequential");
170 Enumeration e = tasks.elements();
171 Task t = null;
172 while (e.hasMoreElements())
173 {
174 t = (Task)e.nextElement();
175 tc.addTask(t);
176 }
177
178 ((Task)tc).execute();
179 }
180
181 public void execute()
182 throws BuildException
183 {
184 if (list == null && currPath == null) {
185 throw new BuildException("You must have a list or path to iterate through");
186 }
187 if (param == null)
188 throw new BuildException("You must supply a property name to set on each iteration in param");
189 if (target == null)
190 throw new BuildException("You must supply a target to perform");
191
192 Vector values = new Vector();
193
194 // Take Care of the list attribute
195 if (list != null)
196 {
197 StringTokenizer st = new StringTokenizer(list, delimiter);
198
199 while (st.hasMoreTokens())
200 {
201 String tok = st.nextToken();
202 if (trim) tok = tok.trim();
203 values.addElement(tok);
204 }
205 }
206
207 String[] pathElements = new String[0];
208 if (currPath != null) {
209 pathElements = currPath.list();
210 }
211
212 for (int i=0;i<pathElements.length;i++)
213 {
214 if (mapper != null)
215 {
216 FileNameMapper m = mapper.getImplementation();
217 String mapped[] = m.mapFileName(pathElements[i]);
218 for (int j=0;j<mapped.length;j++)
219 values.addElement(mapped[j]);
220 }
221 else
222 {
223 values.addElement(new File(pathElements[i]));
224 }
225 }
226
227 Vector tasks = new Vector();
228
229 int sz = values.size();
230 CallTarget ct = null;
231 Object val = null;
232 Property p = null;
233
234 for (int i = 0; i < sz; i++) {
235 val = values.elementAt(i);
236 ct = createCallTarget();
237 p = ct.createParam();
238 p.setName(param);
239
240 if (val instanceof File)
241 p.setLocation((File)val);
242 else
243 p.setValue((String)val);
244
245 tasks.addElement(ct);
246 }
247
248 if (parallel && maxThreads > 1)
249 {
250 executeParallel(tasks);
251 }
252 else
253 {
254 executeSequential(tasks);
255 }
256 }
257
258 public void setTrim(boolean trim)
259 {
260 this.trim = trim;
261 }
262
263 public void setList(String list)
264 {
265 this.list = list;
266 }
267
268 public void setDelimiter(String delimiter)
269 {
270 this.delimiter = delimiter;
271 }
272
273 public void setParam(String param)
274 {
275 this.param = param;
276 }
277
278 public void setTarget(String target)
279 {
280 this.target = target;
281 }
282
283 public void setParallel(boolean parallel)
284 {
285 this.parallel = parallel;
286 }
287
288 /**
289 * Corresponds to <code>&lt;antcall&gt;</code>'s <code>inheritall</code>
290 * attribute.
291 */
292 public void setInheritall(boolean b) {
293 this.inheritAll = b;
294 }
295
296 /**
297 * Corresponds to <code>&lt;antcall&gt;</code>'s <code>inheritrefs</code>
298 * attribute.
299 */
300 public void setInheritrefs(boolean b) {
301 this.inheritRefs = b;
302 }
303
304
305 /***
306 * Set the maximum amount of threads we're going to allow
307 * at once to execute
308 * @param maxThreads
309 */
310 public void setMaxThreads(int maxThreads)
311 {
312 this.maxThreads = maxThreads;
313 }
314
315
316 /**
317 * Corresponds to <code>&lt;antcall&gt;</code>'s nested
318 * <code>&lt;param&gt;</code> element.
319 */
320 public void addParam(Property p) {
321 params.addElement(p);
322 }
323
324 /**
325 * Corresponds to <code>&lt;antcall&gt;</code>'s nested
326 * <code>&lt;reference&gt;</code> element.
327 */
328 public void addReference(Ant.Reference r) {
329 references.addElement(r);
330 }
331
332 /**
333 * @deprecated Use createPath instead.
334 */
335 public void addFileset(FileSet set)
336 {
337 log("The nested fileset element is deprectated, use a nested path "
338 + "instead",
339 Project.MSG_WARN);
340 createPath().addFileset(set);
341 }
342
343 public Path createPath() {
344 if (currPath == null) {
345 currPath = new Path(getProject());
346 }
347 return currPath;
348 }
349
350 public Mapper createMapper()
351 {
352 mapper = new Mapper(getProject());
353 return mapper;
354 }
355
356 private CallTarget createCallTarget() {
357 CallTarget ct = (CallTarget) getProject().createTask("antcall");
358 ct.setOwningTarget(getOwningTarget());
359 ct.init();
360 ct.setTarget(target);
361 ct.setInheritAll(inheritAll);
362 ct.setInheritRefs(inheritRefs);
363 Enumeration e = params.elements();
364 while (e.hasMoreElements()) {
365 Property param = (Property) e.nextElement();
366 Property toSet = ct.createParam();
367 toSet.setName(param.getName());
368 if (param.getValue() != null) {
369 toSet.setValue(param.getValue());
370 }
371 if (param.getFile() != null) {
372 toSet.setFile(param.getFile());
373 }
374 if (param.getResource() != null) {
375 toSet.setResource(param.getResource());
376 }
377 if (param.getPrefix() != null) {
378 toSet.setPrefix(param.getPrefix());
379 }
380 if (param.getRefid() != null) {
381 toSet.setRefid(param.getRefid());
382 }
383 if (param.getEnvironment() != null) {
384 toSet.setEnvironment(param.getEnvironment());
385 }
386 if (param.getClasspath() != null) {
387 toSet.setClasspath(param.getClasspath());
388 }
389 }
390
391 e = references.elements();
392 while (e.hasMoreElements()) {
393 ct.addReference((Ant.Reference) e.nextElement());
394 }
395
396 return ct;
397 }
398
399 protected void handleOutput(String line)
400 {
401 try {
402 super.handleOutput(line);
403 }
404 // This is needed so we can run with 1.5 and 1.5.1
405 catch (IllegalAccessError e) {
406 super.handleOutput(line);
407 }
408 }
409
410 protected void handleErrorOutput(String line)
411 {
412 try {
413 super.handleErrorOutput(line);
414 }
415 // This is needed so we can run with 1.5 and 1.5.1
416 catch (IllegalAccessError e) {
417 super.handleErrorOutput(line);
418 }
419 }
420
421 }
422
423