source: release-kits/wirk3/ant-scripts/tasks/antelope/src/ise/antelope/tasks/AntFetch.java@ 15023

Last change on this file since 15023 was 15023, checked in by oranfry, 16 years ago

did the bulk of the work on wirk3

File size: 21.4 KB
Line 
1/*
2 * The Apache Software License, Version 1.1
3 *
4 * Copyright (c) 2000-2002 The Apache Software Foundation. All rights
5 * reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 *
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 *
14 * 2. Redistributions in binary form must reproduce the above copyright
15 * notice, this list of conditions and the following disclaimer in
16 * the documentation and/or other materials provided with the
17 * distribution.
18 *
19 * 3. The end-user documentation included with the redistribution, if
20 * any, must include the following acknowlegement:
21 * "This product includes software developed by the
22 * Apache Software Foundation (http://www.apache.org/)."
23 * Alternately, this acknowlegement may appear in the software itself,
24 * if and wherever such third-party acknowlegements normally appear.
25 *
26 * 4. The names "The Jakarta Project", "Ant", and "Apache Software
27 * Foundation" must not be used to endorse or promote products derived
28 * from this software without prior written permission. For written
29 * permission, please contact [email protected].
30 *
31 * 5. Products derived from this software may not be called "Apache"
32 * nor may "Apache" appear in their names without prior written
33 * permission of the Apache Group.
34 *
35 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
36 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
37 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
38 * DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
39 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
40 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
41 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
42 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
43 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
44 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
45 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
46 * SUCH DAMAGE.
47 * ====================================================================
48 *
49 * This software consists of voluntary contributions made by many
50 * individuals on behalf of the Apache Software Foundation. For more
51 * information on the Apache Software Foundation, please see
52 * <http://www.apache.org/>.
53 */
54package ise.antelope.tasks;
55
56import java.io.File;
57import java.io.FileOutputStream;
58import java.io.IOException;
59import java.io.PrintStream;
60import java.lang.reflect.Method;
61import java.util.Enumeration;
62import java.util.Hashtable;
63import java.util.StringTokenizer;
64import java.util.Vector;
65import org.apache.tools.ant.BuildException;
66import org.apache.tools.ant.BuildListener;
67import org.apache.tools.ant.DefaultLogger;
68import org.apache.tools.ant.Project;
69import org.apache.tools.ant.ProjectComponent;
70import org.apache.tools.ant.ProjectHelper;
71
72import org.apache.tools.ant.Task;
73
74import org.apache.tools.ant.taskdefs.Property;
75import org.apache.tools.ant.util.FileUtils;
76
77/**
78 * Identical (copy and paste, even) to the 'Ant' task, with the exception that
79 * properties from the new project can be copied back into the original project.
80 * Build a sub-project. <pre>
81 * &lt;target name=&quot;foo&quot; depends=&quot;init&quot;&gt;
82 * &lt;ant antfile=&quot;build.xml&quot; target=&quot;bar&quot; &gt;
83 * &lt;property name=&quot;property1&quot; value=&quot;aaaaa&quot; /&gt;
84 * &lt;property name=&quot;foo&quot; value=&quot;baz&quot; /&gt;
85 * &lt;/ant&gt;</SPAN> &lt;/target&gt;</SPAN> &lt;target name=&quot;bar&quot;
86 * depends=&quot;init&quot;&gt; &lt;echo message=&quot;prop is ${property1}
87 * ${foo}&quot; /&gt; &lt;/target&gt; </pre>
88 *
89 * @author [email protected]
90 * @author Dale Anson, [email protected]
91 * @since Ant 1.1
92 * @ant.task category="control"
93 */
94public class AntFetch extends Task {
95
96 /** the basedir where is executed the build file */
97 private File dir = null;
98
99 /**
100 * the build.xml file (can be absolute) in this case dir will be ignored
101 */
102 private String antFile = null;
103
104 /** the target to call if any */
105 private String target = null;
106
107 /** the output */
108 private String output = null;
109
110 /** should we inherit properties from the parent ? */
111 private boolean inheritAll = true;
112
113 /** should we inherit references from the parent ? */
114 private boolean inheritRefs = false;
115
116 /** the properties to pass to the new project */
117 private Vector properties = new Vector();
118
119 /** the references to pass to the new project */
120 private Vector references = new Vector();
121
122 /** the temporary project created to run the build file */
123 private Project newProject;
124
125 /** The stream to which output is to be written. */
126 private PrintStream out = null;
127
128 /** the name of the property to fetch from the new project */
129 private String returnName = null;
130
131
132 /**
133 * If true, pass all properties to the new Ant project. Defaults to true.
134 *
135 * @param value The new inheritAll value
136 */
137 public void setInheritAll( boolean value ) {
138 inheritAll = value;
139 }
140
141
142 /**
143 * If true, pass all references to the new Ant project. Defaults to false.
144 *
145 * @param value The new inheritRefs value
146 */
147 public void setInheritRefs( boolean value ) {
148 inheritRefs = value;
149 }
150
151
152 /** Creates a Project instance for the project to call. */
153 public void init() {
154 newProject = new Project();
155 newProject.setJavaVersionProperty();
156 newProject.addTaskDefinition( "property",
157 (Class)getProject().getTaskDefinitions()
158 .get( "property" ) );
159 }
160
161
162 /**
163 * Called in execute or createProperty if newProject is null. <p>
164 *
165 * This can happen if the same instance of this task is run twice as
166 * newProject is set to null at the end of execute (to save memory and help
167 * the GC).</p> <p>
168 *
169 * Sets all properties that have been defined as nested property elements.
170 * </p>
171 */
172 private void reinit() {
173 init();
174 final int count = properties.size();
175 for ( int i = 0; i < count; i++ ) {
176 Property p = (Property)properties.elementAt( i );
177 Property newP = (Property)newProject.createTask( "property" );
178 newP.setName( p.getName() );
179 if ( p.getValue() != null ) {
180 newP.setValue( p.getValue() );
181 }
182 if ( p.getFile() != null ) {
183 newP.setFile( p.getFile() );
184 }
185 if ( p.getResource() != null ) {
186 newP.setResource( p.getResource() );
187 }
188 if ( p.getPrefix() != null ) {
189 newP.setPrefix( p.getPrefix() );
190 }
191 if ( p.getRefid() != null ) {
192 newP.setRefid( p.getRefid() );
193 }
194 if ( p.getEnvironment() != null ) {
195 newP.setEnvironment( p.getEnvironment() );
196 }
197 if ( p.getClasspath() != null ) {
198 newP.setClasspath( p.getClasspath() );
199 }
200 properties.setElementAt( newP, i );
201 }
202 }
203
204
205 /**
206 * Attaches the build listeners of the current project to the new project,
207 * configures a possible logfile, transfers task and data-type definitions,
208 * transfers properties (either all or just the ones specified as user
209 * properties to the current project, depending on inheritall), transfers the
210 * input handler.
211 */
212 private void initializeProject() {
213 newProject.setInputHandler( getProject().getInputHandler() );
214
215 Vector listeners = getProject().getBuildListeners();
216 final int count = listeners.size();
217 for ( int i = 0; i < count; i++ ) {
218 newProject.addBuildListener( (BuildListener)listeners.elementAt( i ) );
219 }
220
221 if ( output != null ) {
222 File outfile = null;
223 if ( dir != null ) {
224 outfile = FileUtils.newFileUtils().resolveFile( dir, output );
225 }
226 else {
227 outfile = getProject().resolveFile( output );
228 }
229 try {
230 out = new PrintStream( new FileOutputStream( outfile ) );
231 DefaultLogger logger = new DefaultLogger();
232 logger.setMessageOutputLevel( Project.MSG_INFO );
233 logger.setOutputPrintStream( out );
234 logger.setErrorPrintStream( out );
235 newProject.addBuildListener( logger );
236 }
237 catch ( IOException ex ) {
238 log( "Ant: Can't set output to " + output );
239 }
240 }
241
242 Hashtable taskdefs = getProject().getTaskDefinitions();
243 Enumeration et = taskdefs.keys();
244 while ( et.hasMoreElements() ) {
245 String taskName = (String)et.nextElement();
246 if ( taskName.equals( "property" ) ) {
247 // we have already added this taskdef in #init
248 continue;
249 }
250 Class taskClass = (Class)taskdefs.get( taskName );
251 newProject.addTaskDefinition( taskName, taskClass );
252 }
253
254 Hashtable typedefs = getProject().getDataTypeDefinitions();
255 Enumeration e = typedefs.keys();
256 while ( e.hasMoreElements() ) {
257 String typeName = (String)e.nextElement();
258 Class typeClass = (Class)typedefs.get( typeName );
259 newProject.addDataTypeDefinition( typeName, typeClass );
260 }
261
262 // set user-defined properties
263 getProject().copyUserProperties( newProject );
264
265 if ( !inheritAll ) {
266 // set Java built-in properties separately,
267 // b/c we won't inherit them.
268 newProject.setSystemProperties();
269
270 }
271 else {
272 // set all properties from calling project
273
274 Hashtable props = getProject().getProperties();
275 e = props.keys();
276 while ( e.hasMoreElements() ) {
277 String arg = e.nextElement().toString();
278 if ( "basedir".equals( arg ) || "ant.file".equals( arg ) ) {
279 // basedir and ant.file get special treatment in execute()
280 continue;
281 }
282
283 String value = props.get( arg ).toString();
284 // don't re-set user properties, avoid the warning message
285 if ( newProject.getProperty( arg ) == null ) {
286 // no user property
287 newProject.setNewProperty( arg, value );
288 }
289 }
290 }
291 }
292
293
294 /**
295 * Pass output sent to System.out to the new project.
296 *
297 * @param line Description of the Parameter
298 * @since Ant 1.5
299 */
300 protected void handleOutput( String line ) {
301 if ( newProject != null ) {
302 newProject.demuxOutput( line, false );
303 }
304 else {
305 super.handleOutput( line );
306 }
307 }
308
309
310 /**
311 * Pass output sent to System.err to the new project.
312 *
313 * @param line Description of the Parameter
314 * @since Ant 1.5
315 */
316 protected void handleErrorOutput( String line ) {
317 if ( newProject != null ) {
318 newProject.demuxOutput( line, true );
319 }
320 else {
321 super.handleErrorOutput( line );
322 }
323 }
324
325
326 /**
327 * Do the execution.
328 *
329 * @exception BuildException Description of the Exception
330 */
331 public void execute() throws BuildException {
332 File savedDir = dir;
333 String savedAntFile = antFile;
334 String savedTarget = target;
335 try {
336 if ( newProject == null ) {
337 reinit();
338 }
339
340 if ( ( dir == null ) && ( inheritAll ) ) {
341 dir = getProject().getBaseDir();
342 }
343
344 initializeProject();
345
346 if ( dir != null ) {
347 newProject.setBaseDir( dir );
348 if ( savedDir != null ) { // has been set explicitly
349 newProject.setInheritedProperty( "basedir",
350 dir.getAbsolutePath() );
351 }
352 }
353 else {
354 dir = getProject().getBaseDir();
355 }
356
357 overrideProperties();
358
359 if ( antFile == null ) {
360 antFile = "build.xml";
361 }
362
363 File file = FileUtils.newFileUtils().resolveFile( dir, antFile );
364 antFile = file.getAbsolutePath();
365
366 log( "calling target " + ( target != null ? target : "[default]" )
367 + " in build file " + antFile.toString(),
368 Project.MSG_VERBOSE );
369 newProject.setUserProperty( "ant.file", antFile );
370 ProjectHelper.getProjectHelper().parse( newProject, new File( antFile ) );
371
372 if ( target == null ) {
373 target = newProject.getDefaultTarget();
374 }
375
376 addReferences();
377
378 // Are we trying to call the target in which we are defined?
379 if ( newProject.getBaseDir().equals( getProject().getBaseDir() ) &&
380 newProject.getProperty( "ant.file" ).equals( getProject().getProperty( "ant.file" ) ) &&
381 getOwningTarget() != null &&
382 target.equals( this.getOwningTarget().getName() ) ) {
383
384 throw new BuildException( "ant task calling its own parent "
385 + "target" );
386 }
387
388 newProject.executeTarget( target );
389
390 // copy back the props if possible
391 if ( returnName != null ) {
392 StringTokenizer st = new StringTokenizer( returnName, "," );
393 while ( st.hasMoreTokens() ) {
394 String name = st.nextToken().trim();
395 String value = newProject.getUserProperty( name );
396 if ( value != null ) {
397 getProject().setUserProperty( name, value );
398 }
399 else {
400 value = newProject.getProperty( name );
401 if ( value != null ) {
402 getProject().setProperty( name, value );
403 }
404 }
405 }
406 }
407 }
408 finally {
409 // help the gc
410 newProject = null;
411 if ( output != null && out != null ) {
412 try {
413 out.close();
414 }
415 catch ( final Exception e ) {
416 //ignore
417 }
418 }
419 dir = savedDir;
420 antFile = savedAntFile;
421 target = savedTarget;
422 }
423 }
424
425
426 /**
427 * Override the properties in the new project with the one explicitly defined
428 * as nested elements here.
429 *
430 * @exception BuildException Description of the Exception
431 */
432 private void overrideProperties() throws BuildException {
433 Enumeration e = properties.elements();
434 while ( e.hasMoreElements() ) {
435 Property p = (Property)e.nextElement();
436 p.setProject( newProject );
437 p.execute();
438 }
439 getProject().copyInheritedProperties( newProject );
440 }
441
442
443 /**
444 * Add the references explicitly defined as nested elements to the new
445 * project. Also copy over all references that don't override existing
446 * references in the new project if inheritrefs has been requested.
447 *
448 * @exception BuildException Description of the Exception
449 */
450 private void addReferences() throws BuildException {
451 Hashtable thisReferences = (Hashtable)getProject().getReferences().clone();
452 Hashtable newReferences = newProject.getReferences();
453 Enumeration e;
454 if ( references.size() > 0 ) {
455 for ( e = references.elements(); e.hasMoreElements(); ) {
456 Reference ref = (Reference)e.nextElement();
457 String refid = ref.getRefId();
458 if ( refid == null ) {
459 throw new BuildException( "the refid attribute is required"
460 + " for reference elements" );
461 }
462 if ( !thisReferences.containsKey( refid ) ) {
463 log( "Parent project doesn't contain any reference '"
464 + refid + "'",
465 Project.MSG_WARN );
466 continue;
467 }
468
469 thisReferences.remove( refid );
470 String toRefid = ref.getToRefid();
471 if ( toRefid == null ) {
472 toRefid = refid;
473 }
474 copyReference( refid, toRefid );
475 }
476 }
477
478 // Now add all references that are not defined in the
479 // subproject, if inheritRefs is true
480 if ( inheritRefs ) {
481 for ( e = thisReferences.keys(); e.hasMoreElements(); ) {
482 String key = (String)e.nextElement();
483 if ( newReferences.containsKey( key ) ) {
484 continue;
485 }
486 copyReference( key, key );
487 }
488 }
489 }
490
491
492 /**
493 * Try to clone and reconfigure the object referenced by oldkey in the parent
494 * project and add it to the new project with the key newkey. <p>
495 *
496 * If we cannot clone it, copy the referenced object itself and keep our
497 * fingers crossed.</p>
498 *
499 * @param oldKey Description of the Parameter
500 * @param newKey Description of the Parameter
501 */
502 private void copyReference( String oldKey, String newKey ) {
503 Object orig = getProject().getReference( oldKey );
504 Class c = orig.getClass();
505 Object copy = orig;
506 try {
507 Method cloneM = c.getMethod( "clone", new Class[0] );
508 if ( cloneM != null ) {
509 copy = cloneM.invoke( orig, new Object[0] );
510 }
511 }
512 catch ( Exception e ) {
513 // not Clonable
514 }
515
516 if ( copy instanceof ProjectComponent ) {
517 ( (ProjectComponent)copy ).setProject( newProject );
518 }
519 else {
520 try {
521 Method setProjectM =
522 c.getMethod( "setProject", new Class[]{Project.class} );
523 if ( setProjectM != null ) {
524 setProjectM.invoke( copy, new Object[]{newProject} );
525 }
526 }
527 catch ( NoSuchMethodException e ) {
528 // ignore this if the class being referenced does not have
529 // a set project method.
530 }
531 catch ( Exception e2 ) {
532 String msg = "Error setting new project instance for "
533 + "reference with id " + oldKey;
534 throw new BuildException( msg, e2, getLocation() );
535 }
536 }
537 newProject.addReference( newKey, copy );
538 }
539
540
541 /**
542 * The directory to use as a base directory for the new Ant project. Defaults
543 * to the current project's basedir, unless inheritall has been set to false,
544 * in which case it doesn't have a default value. This will override the
545 * basedir setting of the called project.
546 *
547 * @param d The new dir value
548 */
549 public void setDir( File d ) {
550 this.dir = d;
551 }
552
553
554 /**
555 * The build file to use. Defaults to "build.xml". This file is expected to
556 * be a filename relative to the dir attribute given.
557 *
558 * @param s The new antfile value
559 */
560 public void setAntfile( String s ) {
561 // @note: it is a string and not a file to handle relative/absolute
562 // otherwise a relative file will be resolved based on the current
563 // basedir.
564 this.antFile = s;
565 }
566
567
568 /**
569 * The target of the new Ant project to execute. Defaults to the new
570 * project's default target.
571 *
572 * @param s The new target value
573 */
574 public void setTarget( String s ) {
575 this.target = s;
576 }
577
578
579 /**
580 * Filename to write the output to. This is relative to the value of the dir
581 * attribute if it has been set or to the base directory of the current
582 * project otherwise.
583 *
584 * @param s The new output value
585 */
586 public void setOutput( String s ) {
587 this.output = s;
588 }
589
590
591 /**
592 * Property to pass to the new project. The property is passed as a 'user
593 * property'
594 *
595 * @return Description of the Return Value
596 */
597 public Property createProperty() {
598 if ( newProject == null ) {
599 reinit();
600 }
601 /*
602 * Property p = new Property( true, getProject() );
603 */
604 Property p = new Property();
605 p.setProject( newProject );
606 p.setTaskName( "property" );
607 properties.addElement( p );
608 return p;
609 }
610
611
612 /**
613 * Set the property or properties that are set in the new project to be
614 * transfered back to the original project. As with all properties, if the
615 * property already exists in the original project, it will not be overridden
616 * by a different value from the new project.
617 *
618 * @param r the name of a property in the new project to set in the original
619 * project. This may be a comma separate list of properties.
620 */
621 public void setReturn( String r ) {
622 returnName = r;
623 }
624
625
626 /**
627 * Reference element identifying a data type to carry over to the new
628 * project.
629 *
630 * @param r The feature to be added to the Reference attribute
631 */
632 public void addReference( Reference r ) {
633 references.addElement( r );
634 }
635
636
637 /**
638 * Helper class that implements the nested &lt;reference&gt; element of
639 * &lt;ant&gt; and &lt;antcall&gt;.
640 *
641 * @author danson
642 */
643 public static class Reference
644 extends org.apache.tools.ant.types.Reference {
645
646 /** Creates a reference to be configured by Ant */
647 public Reference() {
648 super();
649 }
650
651
652 private String targetid = null;
653
654
655 /**
656 * Set the id that this reference to be stored under in the new project.
657 *
658 * @param targetid the id under which this reference will be passed to
659 * the new project
660 */
661 public void setToRefid( String targetid ) {
662 this.targetid = targetid;
663 }
664
665
666 /**
667 * Get the id under which this reference will be stored in the new project
668 *
669 * @return the id of the reference in the new project.
670 */
671 public String getToRefid() {
672 return targetid;
673 }
674 }
675}
Note: See TracBrowser for help on using the repository browser.