Debian Codegraph @

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