source: release-kits/lirk3/ant-scripts/tasks/antelope/src/ise/antelope/tasks/AntCallBack.java@ 14982

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

initial import of LiRK3

File size: 21.7 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 * Further modified to emulate "antcall". 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 AntCallBack 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().get( "property" ) );
158 }
159
160
161 /**
162 * Called in execute or createProperty if newProject is null. <p>
163 *
164 * This can happen if the same instance of this task is run twice as
165 * newProject is set to null at the end of execute (to save memory and help
166 * the GC).</p> <p>
167 *
168 * Sets all properties that have been defined as nested property elements.
169 * </p>
170 */
171 private void reinit() {
172 init();
173 final int count = properties.size();
174 for ( int i = 0; i < count; i++ ) {
175 Property p = (Property)properties.elementAt( i );
176 Property newP = (Property)newProject.createTask( "property" );
177 newP.setName( p.getName() );
178 if ( p.getValue() != null ) {
179 newP.setValue( p.getValue() );
180 }
181 if ( p.getFile() != null ) {
182 newP.setFile( p.getFile() );
183 }
184 if ( p.getResource() != null ) {
185 newP.setResource( p.getResource() );
186 }
187 if ( p.getPrefix() != null ) {
188 newP.setPrefix( p.getPrefix() );
189 }
190 if ( p.getRefid() != null ) {
191 newP.setRefid( p.getRefid() );
192 }
193 if ( p.getEnvironment() != null ) {
194 newP.setEnvironment( p.getEnvironment() );
195 }
196 if ( p.getClasspath() != null ) {
197 newP.setClasspath( p.getClasspath() );
198 }
199 properties.setElementAt( newP, i );
200 }
201 }
202
203
204 /**
205 * Attaches the build listeners of the current project to the new project,
206 * configures a possible logfile, transfers task and data-type definitions,
207 * transfers properties (either all or just the ones specified as user
208 * properties to the current project, depending on inheritall), transfers the
209 * input handler.
210 */
211 private void initializeProject() {
212 newProject.setInputHandler( getProject().getInputHandler() );
213
214 Vector listeners = getProject().getBuildListeners();
215 final int count = listeners.size();
216 for ( int i = 0; i < count; i++ ) {
217 newProject.addBuildListener( (BuildListener)listeners.elementAt( i ) );
218 }
219
220 if ( output != null ) {
221 File outfile = null;
222 if ( dir != null ) {
223 outfile = FileUtils.newFileUtils().resolveFile( dir, output );
224 }
225 else {
226 outfile = getProject().resolveFile( output );
227 }
228 try {
229 out = new PrintStream( new FileOutputStream( outfile ) );
230 DefaultLogger logger = new DefaultLogger();
231 logger.setMessageOutputLevel( Project.MSG_INFO );
232 logger.setOutputPrintStream( out );
233 logger.setErrorPrintStream( out );
234 newProject.addBuildListener( logger );
235 }
236 catch ( IOException ex ) {
237 log( "Ant: Can't set output to " + output );
238 }
239 }
240
241 Hashtable taskdefs = getProject().getTaskDefinitions();
242 Enumeration et = taskdefs.keys();
243 while ( et.hasMoreElements() ) {
244 String taskName = (String)et.nextElement();
245 if ( taskName.equals( "property" ) ) {
246 // we have already added this taskdef in #init
247 continue;
248 }
249 Class taskClass = (Class)taskdefs.get( taskName );
250 newProject.addTaskDefinition( taskName, taskClass );
251 }
252
253 Hashtable typedefs = getProject().getDataTypeDefinitions();
254 Enumeration e = typedefs.keys();
255 while ( e.hasMoreElements() ) {
256 String typeName = (String)e.nextElement();
257 Class typeClass = (Class)typedefs.get( typeName );
258 newProject.addDataTypeDefinition( typeName, typeClass );
259 }
260
261 // set user-defined properties
262 getProject().copyUserProperties( newProject );
263
264 if ( !inheritAll ) {
265 // set Java built-in properties separately,
266 // b/c we won't inherit them.
267 newProject.setSystemProperties();
268
269 }
270 else {
271 // set all properties from calling project
272
273 Hashtable props = getProject().getProperties();
274 e = props.keys();
275 while ( e.hasMoreElements() ) {
276 String arg = e.nextElement().toString();
277 if ( "basedir".equals( arg ) || "ant.file".equals( arg ) ) {
278 // basedir and ant.file get special treatment in execute()
279 continue;
280 }
281
282 String value = props.get( arg ).toString();
283 // don't re-set user properties, avoid the warning message
284 if ( newProject.getProperty( arg ) == null ) {
285 // no user property
286 newProject.setNewProperty( arg, value );
287 }
288 }
289 }
290 }
291
292
293 /**
294 * Pass output sent to System.out to the new project.
295 *
296 * @param line Description of the Parameter
297 * @since Ant 1.5
298 */
299 protected void handleOutput( String line ) {
300 if ( newProject != null ) {
301 newProject.demuxOutput( line, false );
302 }
303 else {
304 super.handleOutput( line );
305 }
306 }
307
308
309 /**
310 * Pass output sent to System.err to the new project.
311 *
312 * @param line Description of the Parameter
313 * @since Ant 1.5
314 */
315 protected void handleErrorOutput( String line ) {
316 if ( newProject != null ) {
317 newProject.demuxOutput( line, true );
318 }
319 else {
320 super.handleErrorOutput( line );
321 }
322 }
323
324
325 /**
326 * Do the execution.
327 *
328 * @exception BuildException Description of the Exception
329 */
330 public void execute() throws BuildException {
331 setAntfile( getProject().getProperty( "ant.file" ) );
332
333 File savedDir = dir;
334 String savedAntFile = antFile;
335 String savedTarget = target;
336 try {
337 if ( newProject == null ) {
338 reinit();
339 }
340
341 if ( ( dir == null ) && ( inheritAll ) ) {
342 dir = getProject().getBaseDir();
343 }
344
345 initializeProject();
346
347 if ( dir != null ) {
348 newProject.setBaseDir( dir );
349 if ( savedDir != null ) { // has been set explicitly
350 newProject.setInheritedProperty( "basedir",
351 dir.getAbsolutePath() );
352 }
353 }
354 else {
355 dir = getProject().getBaseDir();
356 }
357
358 overrideProperties();
359
360 if ( antFile == null ) {
361 throw new BuildException( "Attribute target is required.",
362 getLocation() );
363 //antFile = "build.xml";
364 }
365
366 File file = FileUtils.newFileUtils().resolveFile( dir, antFile );
367 antFile = file.getAbsolutePath();
368
369 log( "calling target " + ( target != null ? target : "[default]" )
370 + " in build file " + antFile.toString(),
371 Project.MSG_VERBOSE );
372 newProject.setUserProperty( "ant.file", antFile );
373 ProjectHelper.getProjectHelper().parse( newProject, new File( antFile ) );
374
375 if ( target == null ) {
376 target = newProject.getDefaultTarget();
377 }
378
379 addReferences();
380
381 // Are we trying to call the target in which we are defined?
382 if ( newProject.getBaseDir().equals( getProject().getBaseDir() ) &&
383 newProject.getProperty( "ant.file" ).equals( getProject().getProperty( "ant.file" ) ) &&
384 getOwningTarget() != null &&
385 target.equals( this.getOwningTarget().getName() ) ) {
386
387 throw new BuildException( "antcallback task calling its own parent "
388 + "target" );
389 }
390
391 newProject.executeTarget( target );
392
393 // copy back the props if possible
394 if ( returnName != null ) {
395 StringTokenizer st = new StringTokenizer( returnName, "," );
396 while ( st.hasMoreTokens() ) {
397 String name = st.nextToken().trim();
398 String value = newProject.getUserProperty( name );
399 if ( value != null ) {
400 getProject().setUserProperty( name, value );
401 }
402 else {
403 value = newProject.getProperty( name );
404 if ( value != null ) {
405 getProject().setProperty( name, value );
406 }
407 }
408 }
409 }
410 }
411 finally {
412 // help the gc
413 newProject = null;
414 if ( output != null && out != null ) {
415 try {
416 out.close();
417 }
418 catch ( final Exception e ) {
419 //ignore
420 }
421 }
422 dir = savedDir;
423 antFile = savedAntFile;
424 target = savedTarget;
425 }
426 }
427
428
429 /**
430 * Override the properties in the new project with the one explicitly defined
431 * as nested elements here.
432 *
433 * @exception BuildException Description of the Exception
434 */
435 private void overrideProperties() throws BuildException {
436 Enumeration e = properties.elements();
437 while ( e.hasMoreElements() ) {
438 Property p = (Property)e.nextElement();
439 p.setProject( newProject );
440 p.execute();
441 }
442 getProject().copyInheritedProperties( newProject );
443 }
444
445
446 /**
447 * Add the references explicitly defined as nested elements to the new
448 * project. Also copy over all references that don't override existing
449 * references in the new project if inheritrefs has been requested.
450 *
451 * @exception BuildException Description of the Exception
452 */
453 private void addReferences() throws BuildException {
454 Hashtable thisReferences = (Hashtable)getProject().getReferences().clone();
455 Hashtable newReferences = newProject.getReferences();
456 Enumeration e;
457 if ( references.size() > 0 ) {
458 for ( e = references.elements(); e.hasMoreElements(); ) {
459 Reference ref = (Reference)e.nextElement();
460 String refid = ref.getRefId();
461 if ( refid == null ) {
462 throw new BuildException( "the refid attribute is required"
463 + " for reference elements" );
464 }
465 if ( !thisReferences.containsKey( refid ) ) {
466 log( "Parent project doesn't contain any reference '"
467 + refid + "'",
468 Project.MSG_WARN );
469 continue;
470 }
471
472 thisReferences.remove( refid );
473 String toRefid = ref.getToRefid();
474 if ( toRefid == null ) {
475 toRefid = refid;
476 }
477 copyReference( refid, toRefid );
478 }
479 }
480
481 // Now add all references that are not defined in the
482 // subproject, if inheritRefs is true
483 if ( inheritRefs ) {
484 for ( e = thisReferences.keys(); e.hasMoreElements(); ) {
485 String key = (String)e.nextElement();
486 if ( newReferences.containsKey( key ) ) {
487 continue;
488 }
489 copyReference( key, key );
490 }
491 }
492 }
493
494
495 /**
496 * Try to clone and reconfigure the object referenced by oldkey in the parent
497 * project and add it to the new project with the key newkey. <p>
498 *
499 * If we cannot clone it, copy the referenced object itself and keep our
500 * fingers crossed.</p>
501 *
502 * @param oldKey Description of the Parameter
503 * @param newKey Description of the Parameter
504 */
505 private void copyReference( String oldKey, String newKey ) {
506 Object orig = getProject().getReference( oldKey );
507 Class c = orig.getClass();
508 Object copy = orig;
509 try {
510 Method cloneM = c.getMethod( "clone", new Class[0] );
511 if ( cloneM != null ) {
512 copy = cloneM.invoke( orig, new Object[0] );
513 }
514 }
515 catch ( Exception e ) {
516 // not Clonable
517 }
518
519 if ( copy instanceof ProjectComponent ) {
520 ( (ProjectComponent)copy ).setProject( newProject );
521 }
522 else {
523 try {
524 Method setProjectM =
525 c.getMethod( "setProject", new Class[]{Project.class} );
526 if ( setProjectM != null ) {
527 setProjectM.invoke( copy, new Object[]{newProject} );
528 }
529 }
530 catch ( NoSuchMethodException e ) {
531 // ignore this if the class being referenced does not have
532 // a set project method.
533 }
534 catch ( Exception e2 ) {
535 String msg = "Error setting new project instance for "
536 + "reference with id " + oldKey;
537 throw new BuildException( msg, e2, getLocation() );
538 }
539 }
540 newProject.addReference( newKey, copy );
541 }
542
543
544 /**
545 * The directory to use as a base directory for the new Ant project. Defaults
546 * to the current project's basedir, unless inheritall has been set to false,
547 * in which case it doesn't have a default value. This will override the
548 * basedir setting of the called project.
549 *
550 * @param d The new dir value
551 */
552 public void setDir( File d ) {
553 this.dir = d;
554 }
555
556
557 /**
558 * The build file to use. Defaults to "build.xml". This file is expected to
559 * be a filename relative to the dir attribute given.
560 *
561 * @param s The new antfile value
562 */
563 public void setAntfile( String s ) {
564 // @note: it is a string and not a file to handle relative/absolute
565 // otherwise a relative file will be resolved based on the current
566 // basedir.
567 this.antFile = s;
568 }
569
570
571 /**
572 * The target of the new Ant project to execute. Defaults to the new
573 * project's default target.
574 *
575 * @param s The new target value
576 */
577 public void setTarget( String s ) {
578 this.target = s;
579 }
580
581
582 /**
583 * Filename to write the output to. This is relative to the value of the dir
584 * attribute if it has been set or to the base directory of the current
585 * project otherwise.
586 *
587 * @param s The new output value
588 */
589 public void setOutput( String s ) {
590 this.output = s;
591 }
592
593
594 /**
595 * Property to pass to the new project. The property is passed as a 'user
596 * property'
597 *
598 * @return Description of the Return Value
599 */
600 public Property createProperty() {
601 if ( newProject == null ) {
602 reinit();
603 }
604 /*
605 * Property p = new Property( true, getProject() );
606 */
607 Property p = new Property();
608 p.setProject( newProject );
609 p.setTaskName( "property" );
610 properties.addElement( p );
611 return p;
612 }
613
614
615 /**
616 * Property to pass to the invoked target.
617 */
618 public Property createParam() {
619 return createProperty();
620 }
621
622 /**
623 * Set the property or properties that are set in the new project to be
624 * transfered back to the original project. As with all properties, if the
625 * property already exists in the original project, it will not be overridden
626 * by a different value from the new project.
627 *
628 * @param r the name of a property in the new project to set in the original
629 * project. This may be a comma separate list of properties.
630 */
631 public void setReturn( String r ) {
632 returnName = r;
633 }
634
635
636 /**
637 * Reference element identifying a data type to carry over to the new
638 * project.
639 *
640 * @param r The feature to be added to the Reference attribute
641 */
642 public void addReference( Reference r ) {
643 references.addElement( r );
644 }
645
646
647 /**
648 * Helper class that implements the nested &lt;reference&gt; element of
649 * &lt;ant&gt; and &lt;antcall&gt;.
650 *
651 * @author danson
652 */
653 public static class Reference
654 extends org.apache.tools.ant.types.Reference {
655
656 /** Creates a reference to be configured by Ant */
657 public Reference() {
658 super();
659 }
660
661
662 private String targetid = null;
663
664
665 /**
666 * Set the id that this reference to be stored under in the new project.
667 *
668 * @param targetid the id under which this reference will be passed to
669 * the new project
670 */
671 public void setToRefid( String targetid ) {
672 this.targetid = targetid;
673 }
674
675
676 /**
677 * Get the id under which this reference will be stored in the new project
678 *
679 * @return the id of the reference in the new project.
680 */
681 public String getToRefid() {
682 return targetid;
683 }
684 }
685}
686
Note: See TracBrowser for help on using the repository browser.