1. /*
  2. * Copyright 2000-2004 The Apache Software Foundation
  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. */
  17. package org.apache.tools.ant;
  18. import java.io.File;
  19. import java.io.IOException;
  20. import java.io.EOFException;
  21. import java.io.InputStream;
  22. import java.lang.reflect.Method;
  23. import java.lang.reflect.Modifier;
  24. import java.util.Enumeration;
  25. import java.util.Hashtable;
  26. import java.util.Iterator;
  27. import java.util.Properties;
  28. import java.util.Stack;
  29. import java.util.Vector;
  30. import java.util.Set;
  31. import java.util.HashSet;
  32. import org.apache.tools.ant.input.DefaultInputHandler;
  33. import org.apache.tools.ant.input.InputHandler;
  34. import org.apache.tools.ant.types.FilterSet;
  35. import org.apache.tools.ant.types.FilterSetCollection;
  36. import org.apache.tools.ant.types.Description;
  37. import org.apache.tools.ant.types.Path;
  38. import org.apache.tools.ant.util.FileUtils;
  39. import org.apache.tools.ant.util.JavaEnvUtils;
  40. import org.apache.tools.ant.util.StringUtils;
  41. /**
  42. * Central representation of an Ant project. This class defines an
  43. * Ant project with all of its targets, tasks and various other
  44. * properties. It also provides the mechanism to kick off a build using
  45. * a particular target name.
  46. * <p>
  47. * This class also encapsulates methods which allow files to be referred
  48. * to using abstract path names which are translated to native system
  49. * file paths at runtime.
  50. *
  51. * @version $Revision: 1.154.2.10 $
  52. */
  53. public class Project {
  54. /** Message priority of "error". */
  55. public static final int MSG_ERR = 0;
  56. /** Message priority of "warning". */
  57. public static final int MSG_WARN = 1;
  58. /** Message priority of "information". */
  59. public static final int MSG_INFO = 2;
  60. /** Message priority of "verbose". */
  61. public static final int MSG_VERBOSE = 3;
  62. /** Message priority of "debug". */
  63. public static final int MSG_DEBUG = 4;
  64. /**
  65. * Constant for the "visiting" state, used when
  66. * traversing a DFS of target dependencies.
  67. */
  68. private static final String VISITING = "VISITING";
  69. /**
  70. * Constant for the "visited" state, used when
  71. * traversing a DFS of target dependencies.
  72. */
  73. private static final String VISITED = "VISITED";
  74. /**
  75. * The class name of the Ant class loader to use for
  76. * JDK 1.2 and above
  77. */
  78. private static final String ANTCLASSLOADER_JDK12
  79. = "org.apache.tools.ant.loader.AntClassLoader2";
  80. /**
  81. * Version constant for Java 1.0
  82. *
  83. * @deprecated use org.apache.tools.ant.util.JavaEnvUtils instead
  84. */
  85. public static final String JAVA_1_0 = JavaEnvUtils.JAVA_1_0;
  86. /**
  87. * Version constant for Java 1.1
  88. *
  89. * @deprecated use org.apache.tools.ant.util.JavaEnvUtils instead
  90. */
  91. public static final String JAVA_1_1 = JavaEnvUtils.JAVA_1_1;
  92. /**
  93. * Version constant for Java 1.2
  94. *
  95. * @deprecated use org.apache.tools.ant.util.JavaEnvUtils instead
  96. */
  97. public static final String JAVA_1_2 = JavaEnvUtils.JAVA_1_2;
  98. /**
  99. * Version constant for Java 1.3
  100. *
  101. * @deprecated use org.apache.tools.ant.util.JavaEnvUtils instead
  102. */
  103. public static final String JAVA_1_3 = JavaEnvUtils.JAVA_1_3;
  104. /**
  105. * Version constant for Java 1.4
  106. *
  107. * @deprecated use org.apache.tools.ant.util.JavaEnvUtils instead
  108. */
  109. public static final String JAVA_1_4 = JavaEnvUtils.JAVA_1_4;
  110. /** Default filter start token. */
  111. public static final String TOKEN_START = FilterSet.DEFAULT_TOKEN_START;
  112. /** Default filter end token. */
  113. public static final String TOKEN_END = FilterSet.DEFAULT_TOKEN_END;
  114. /** Name of this project. */
  115. private String name;
  116. /** Description for this project (if any). */
  117. private String description;
  118. /** Map of references within the project (paths etc) (String to Object). */
  119. private Hashtable references = new AntRefTable(this);
  120. /** Name of the project's default target. */
  121. private String defaultTarget;
  122. /** Map from target names to targets (String to Target). */
  123. private Hashtable targets = new Hashtable();
  124. /** Set of global filters. */
  125. private FilterSet globalFilterSet = new FilterSet();
  126. {
  127. // Initialize the globalFileSet's project
  128. globalFilterSet.setProject(this);
  129. }
  130. /**
  131. * Wrapper around globalFilterSet. This collection only ever
  132. * contains one FilterSet, but the wrapper is needed in order to
  133. * make it easier to use the FileUtils interface.
  134. */
  135. private FilterSetCollection globalFilters
  136. = new FilterSetCollection(globalFilterSet);
  137. /** Project base directory. */
  138. private File baseDir;
  139. /** List of listeners to notify of build events. */
  140. private Vector listeners = new Vector();
  141. /**
  142. * The Ant core classloader - may be <code>null</code> if using
  143. * parent classloader.
  144. */
  145. private ClassLoader coreLoader = null;
  146. /** Records the latest task to be executed on a thread (Thread to Task). */
  147. private Hashtable threadTasks = new Hashtable();
  148. /** Records the latest task to be executed on a thread Group. */
  149. private Hashtable threadGroupTasks = new Hashtable();
  150. /**
  151. * Called to handle any input requests.
  152. */
  153. private InputHandler inputHandler = null;
  154. /**
  155. * The default input stream used to read any input
  156. */
  157. private InputStream defaultInputStream = null;
  158. /**
  159. * Keep going flag
  160. */
  161. private boolean keepGoingMode = false;
  162. /**
  163. * Sets the input handler
  164. *
  165. * @param handler the InputHandler instance to use for gathering input.
  166. */
  167. public void setInputHandler(InputHandler handler) {
  168. inputHandler = handler;
  169. }
  170. /**
  171. * Set the default System input stream. Normally this stream is set to
  172. * System.in. This inputStream is used when no task input redirection is
  173. * being performed.
  174. *
  175. * @param defaultInputStream the default input stream to use when input
  176. * is requested.
  177. * @since Ant 1.6
  178. */
  179. public void setDefaultInputStream(InputStream defaultInputStream) {
  180. this.defaultInputStream = defaultInputStream;
  181. }
  182. /**
  183. * Get this project's input stream
  184. *
  185. * @return the InputStream instance in use by this Project instance to
  186. * read input
  187. */
  188. public InputStream getDefaultInputStream() {
  189. return defaultInputStream;
  190. }
  191. /**
  192. * Retrieves the current input handler.
  193. *
  194. * @return the InputHandler instance currently in place for the project
  195. * instance.
  196. */
  197. public InputHandler getInputHandler() {
  198. return inputHandler;
  199. }
  200. /** Instance of a utility class to use for file operations. */
  201. private FileUtils fileUtils;
  202. /**
  203. * Flag which catches Listeners which try to use System.out or System.err
  204. */
  205. private boolean loggingMessage = false;
  206. /**
  207. * Creates a new Ant project.
  208. */
  209. public Project() {
  210. fileUtils = FileUtils.newFileUtils();
  211. inputHandler = new DefaultInputHandler();
  212. }
  213. /**
  214. * inits a sub project - used by taskdefs.Ant
  215. * @param subProject the subproject to initialize
  216. */
  217. public void initSubProject(Project subProject) {
  218. ComponentHelper.getComponentHelper(subProject)
  219. .initSubProject(ComponentHelper.getComponentHelper(this));
  220. subProject.setKeepGoingMode(this.isKeepGoingMode());
  221. }
  222. /**
  223. * Initialises the project.
  224. *
  225. * This involves setting the default task definitions and loading the
  226. * system properties.
  227. *
  228. * @exception BuildException if the default task list cannot be loaded
  229. */
  230. public void init() throws BuildException {
  231. setJavaVersionProperty();
  232. ComponentHelper.getComponentHelper(this).initDefaultDefinitions();
  233. setSystemProperties();
  234. }
  235. /**
  236. * Factory method to create a class loader for loading classes
  237. *
  238. * @return an appropriate classloader
  239. */
  240. private AntClassLoader createClassLoader() {
  241. AntClassLoader loader = null;
  242. if (!JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_1)) {
  243. try {
  244. // 1.2+ - create advanced helper dynamically
  245. Class loaderClass
  246. = Class.forName(ANTCLASSLOADER_JDK12);
  247. loader = (AntClassLoader) loaderClass.newInstance();
  248. } catch (Exception e) {
  249. log("Unable to create Class Loader: "
  250. + e.getMessage(), Project.MSG_DEBUG);
  251. }
  252. }
  253. if (loader == null) {
  254. loader = new AntClassLoader();
  255. }
  256. loader.setProject(this);
  257. return loader;
  258. }
  259. /**
  260. * Factory method to create a class loader for loading classes from
  261. * a given path
  262. *
  263. * @param path the path from which classes are to be loaded.
  264. *
  265. * @return an appropriate classloader
  266. */
  267. public AntClassLoader createClassLoader(Path path) {
  268. AntClassLoader loader = createClassLoader();
  269. loader.setClassPath(path);
  270. return loader;
  271. }
  272. /**
  273. * Sets the core classloader for the project. If a <code>null</code>
  274. * classloader is specified, the parent classloader should be used.
  275. *
  276. * @param coreLoader The classloader to use for the project.
  277. * May be <code>null</code>.
  278. */
  279. public void setCoreLoader(ClassLoader coreLoader) {
  280. this.coreLoader = coreLoader;
  281. }
  282. /**
  283. * Returns the core classloader to use for this project.
  284. * This may be <code>null</code>, indicating that
  285. * the parent classloader should be used.
  286. *
  287. * @return the core classloader to use for this project.
  288. *
  289. */
  290. public ClassLoader getCoreLoader() {
  291. return coreLoader;
  292. }
  293. /**
  294. * Adds a build listener to the list. This listener will
  295. * be notified of build events for this project.
  296. *
  297. * @param listener The listener to add to the list.
  298. * Must not be <code>null</code>.
  299. */
  300. public synchronized void addBuildListener(BuildListener listener) {
  301. // create a new Vector to avoid ConcurrentModificationExc when
  302. // the listeners get added/removed while we are in fire
  303. Vector newListeners = getBuildListeners();
  304. newListeners.addElement(listener);
  305. listeners = newListeners;
  306. }
  307. /**
  308. * Removes a build listener from the list. This listener
  309. * will no longer be notified of build events for this project.
  310. *
  311. * @param listener The listener to remove from the list.
  312. * Should not be <code>null</code>.
  313. */
  314. public synchronized void removeBuildListener(BuildListener listener) {
  315. // create a new Vector to avoid ConcurrentModificationExc when
  316. // the listeners get added/removed while we are in fire
  317. Vector newListeners = getBuildListeners();
  318. newListeners.removeElement(listener);
  319. listeners = newListeners;
  320. }
  321. /**
  322. * Returns a copy of the list of build listeners for the project.
  323. *
  324. * @return a list of build listeners for the project
  325. */
  326. public Vector getBuildListeners() {
  327. return (Vector) listeners.clone();
  328. }
  329. /**
  330. * Writes a message to the log with the default log level
  331. * of MSG_INFO
  332. * @param message The text to log. Should not be <code>null</code>.
  333. */
  334. public void log(String message) {
  335. log(message, MSG_INFO);
  336. }
  337. /**
  338. * Writes a project level message to the log with the given log level.
  339. * @param message The text to log. Should not be <code>null</code>.
  340. * @param msgLevel The priority level to log at.
  341. */
  342. public void log(String message, int msgLevel) {
  343. fireMessageLogged(this, message, msgLevel);
  344. }
  345. /**
  346. * Writes a task level message to the log with the given log level.
  347. * @param task The task to use in the log. Must not be <code>null</code>.
  348. * @param message The text to log. Should not be <code>null</code>.
  349. * @param msgLevel The priority level to log at.
  350. */
  351. public void log(Task task, String message, int msgLevel) {
  352. fireMessageLogged(task, message, msgLevel);
  353. }
  354. /**
  355. * Writes a target level message to the log with the given log level.
  356. * @param target The target to use in the log.
  357. * Must not be <code>null</code>.
  358. * @param message The text to log. Should not be <code>null</code>.
  359. * @param msgLevel The priority level to log at.
  360. */
  361. public void log(Target target, String message, int msgLevel) {
  362. fireMessageLogged(target, message, msgLevel);
  363. }
  364. /**
  365. * Returns the set of global filters.
  366. *
  367. * @return the set of global filters
  368. */
  369. public FilterSet getGlobalFilterSet() {
  370. return globalFilterSet;
  371. }
  372. /**
  373. * Sets a property. Any existing property of the same name
  374. * is overwritten, unless it is a user property.
  375. * @param name The name of property to set.
  376. * Must not be <code>null</code>.
  377. * @param value The new value of the property.
  378. * Must not be <code>null</code>.
  379. */
  380. public void setProperty(String name, String value) {
  381. PropertyHelper.getPropertyHelper(this).
  382. setProperty(null, name, value, true);
  383. }
  384. /**
  385. * Sets a property if no value currently exists. If the property
  386. * exists already, a message is logged and the method returns with
  387. * no other effect.
  388. *
  389. * @param name The name of property to set.
  390. * Must not be <code>null</code>.
  391. * @param value The new value of the property.
  392. * Must not be <code>null</code>.
  393. * @since 1.5
  394. */
  395. public void setNewProperty(String name, String value) {
  396. PropertyHelper.getPropertyHelper(this).setNewProperty(null, name,
  397. value);
  398. }
  399. /**
  400. * Sets a user property, which cannot be overwritten by
  401. * set/unset property calls. Any previous value is overwritten.
  402. * @param name The name of property to set.
  403. * Must not be <code>null</code>.
  404. * @param value The new value of the property.
  405. * Must not be <code>null</code>.
  406. * @see #setProperty(String,String)
  407. */
  408. public void setUserProperty(String name, String value) {
  409. PropertyHelper.getPropertyHelper(this).setUserProperty(null, name,
  410. value);
  411. }
  412. /**
  413. * Sets a user property, which cannot be overwritten by set/unset
  414. * property calls. Any previous value is overwritten. Also marks
  415. * these properties as properties that have not come from the
  416. * command line.
  417. *
  418. * @param name The name of property to set.
  419. * Must not be <code>null</code>.
  420. * @param value The new value of the property.
  421. * Must not be <code>null</code>.
  422. * @see #setProperty(String,String)
  423. */
  424. public void setInheritedProperty(String name, String value) {
  425. PropertyHelper ph = PropertyHelper.getPropertyHelper(this);
  426. ph.setInheritedProperty(null, name, value);
  427. }
  428. /**
  429. * Sets a property unless it is already defined as a user property
  430. * (in which case the method returns silently).
  431. *
  432. * @param name The name of the property.
  433. * Must not be <code>null</code>.
  434. * @param value The property value. Must not be <code>null</code>.
  435. */
  436. private void setPropertyInternal(String name, String value) {
  437. PropertyHelper ph = PropertyHelper.getPropertyHelper(this);
  438. ph.setProperty(null, name, value, false);
  439. }
  440. /**
  441. * Returns the value of a property, if it is set.
  442. *
  443. * @param name The name of the property.
  444. * May be <code>null</code>, in which case
  445. * the return value is also <code>null</code>.
  446. * @return the property value, or <code>null</code> for no match
  447. * or if a <code>null</code> name is provided.
  448. */
  449. public String getProperty(String name) {
  450. PropertyHelper ph = PropertyHelper.getPropertyHelper(this);
  451. return (String) ph.getProperty(null, name);
  452. }
  453. /**
  454. * Replaces ${} style constructions in the given value with the
  455. * string value of the corresponding data types.
  456. *
  457. * @param value The string to be scanned for property references.
  458. * May be <code>null</code>.
  459. *
  460. * @return the given string with embedded property names replaced
  461. * by values, or <code>null</code> if the given string is
  462. * <code>null</code>.
  463. *
  464. * @exception BuildException if the given value has an unclosed
  465. * property name, e.g. <code>${xxx</code>
  466. */
  467. public String replaceProperties(String value)
  468. throws BuildException {
  469. PropertyHelper ph = PropertyHelper.getPropertyHelper(this);
  470. return ph.replaceProperties(null, value, null);
  471. }
  472. /**
  473. * Returns the value of a user property, if it is set.
  474. *
  475. * @param name The name of the property.
  476. * May be <code>null</code>, in which case
  477. * the return value is also <code>null</code>.
  478. * @return the property value, or <code>null</code> for no match
  479. * or if a <code>null</code> name is provided.
  480. */
  481. public String getUserProperty(String name) {
  482. PropertyHelper ph = PropertyHelper.getPropertyHelper(this);
  483. return (String) ph.getUserProperty(null, name);
  484. }
  485. /**
  486. * Returns a copy of the properties table.
  487. * @return a hashtable containing all properties
  488. * (including user properties).
  489. */
  490. public Hashtable getProperties() {
  491. PropertyHelper ph = PropertyHelper.getPropertyHelper(this);
  492. return ph.getProperties();
  493. }
  494. /**
  495. * Returns a copy of the user property hashtable
  496. * @return a hashtable containing just the user properties
  497. */
  498. public Hashtable getUserProperties() {
  499. PropertyHelper ph = PropertyHelper.getPropertyHelper(this);
  500. return ph.getUserProperties();
  501. }
  502. /**
  503. * Copies all user properties that have been set on the command
  504. * line or a GUI tool from this instance to the Project instance
  505. * given as the argument.
  506. *
  507. * <p>To copy all "user" properties, you will also have to call
  508. * {@link #copyInheritedProperties copyInheritedProperties}.</p>
  509. *
  510. * @param other the project to copy the properties to. Must not be null.
  511. *
  512. * @since Ant 1.5
  513. */
  514. public void copyUserProperties(Project other) {
  515. PropertyHelper ph = PropertyHelper.getPropertyHelper(this);
  516. ph.copyUserProperties(other);
  517. }
  518. /**
  519. * Copies all user properties that have not been set on the
  520. * command line or a GUI tool from this instance to the Project
  521. * instance given as the argument.
  522. *
  523. * <p>To copy all "user" properties, you will also have to call
  524. * {@link #copyUserProperties copyUserProperties}.</p>
  525. *
  526. * @param other the project to copy the properties to. Must not be null.
  527. *
  528. * @since Ant 1.5
  529. */
  530. public void copyInheritedProperties(Project other) {
  531. PropertyHelper ph = PropertyHelper.getPropertyHelper(this);
  532. ph.copyInheritedProperties(other);
  533. }
  534. /**
  535. * Sets the default target of the project.
  536. *
  537. * @param defaultTarget The name of the default target for this project.
  538. * May be <code>null</code>, indicating that there is
  539. * no default target.
  540. *
  541. * @deprecated use setDefault
  542. * @see #setDefault(String)
  543. */
  544. public void setDefaultTarget(String defaultTarget) {
  545. this.defaultTarget = defaultTarget;
  546. }
  547. /**
  548. * Returns the name of the default target of the project.
  549. * @return name of the default target or
  550. * <code>null</code> if no default has been set.
  551. */
  552. public String getDefaultTarget() {
  553. return defaultTarget;
  554. }
  555. /**
  556. * Sets the default target of the project.
  557. *
  558. * @param defaultTarget The name of the default target for this project.
  559. * May be <code>null</code>, indicating that there is
  560. * no default target.
  561. */
  562. public void setDefault(String defaultTarget) {
  563. this.defaultTarget = defaultTarget;
  564. }
  565. /**
  566. * Sets the name of the project, also setting the user
  567. * property <code>ant.project.name</code>.
  568. *
  569. * @param name The name of the project.
  570. * Must not be <code>null</code>.
  571. */
  572. public void setName(String name) {
  573. setUserProperty("ant.project.name", name);
  574. this.name = name;
  575. }
  576. /**
  577. * Returns the project name, if one has been set.
  578. *
  579. * @return the project name, or <code>null</code> if it hasn't been set.
  580. */
  581. public String getName() {
  582. return name;
  583. }
  584. /**
  585. * Sets the project description.
  586. *
  587. * @param description The description of the project.
  588. * May be <code>null</code>.
  589. */
  590. public void setDescription(String description) {
  591. this.description = description;
  592. }
  593. /**
  594. * Returns the project description, if one has been set.
  595. *
  596. * @return the project description, or <code>null</code> if it hasn't
  597. * been set.
  598. */
  599. public String getDescription() {
  600. if (description == null) {
  601. description = Description.getDescription(this);
  602. }
  603. return description;
  604. }
  605. /**
  606. * Adds a filter to the set of global filters.
  607. *
  608. * @param token The token to filter.
  609. * Must not be <code>null</code>.
  610. * @param value The replacement value.
  611. * Must not be <code>null</code>.
  612. * @deprecated Use getGlobalFilterSet().addFilter(token,value)
  613. *
  614. * @see #getGlobalFilterSet()
  615. * @see FilterSet#addFilter(String,String)
  616. */
  617. public void addFilter(String token, String value) {
  618. if (token == null) {
  619. return;
  620. }
  621. globalFilterSet.addFilter(new FilterSet.Filter(token, value));
  622. }
  623. /**
  624. * Returns a hashtable of global filters, mapping tokens to values.
  625. *
  626. * @return a hashtable of global filters, mapping tokens to values
  627. * (String to String).
  628. *
  629. * @deprecated Use getGlobalFilterSet().getFilterHash()
  630. *
  631. * @see #getGlobalFilterSet()
  632. * @see FilterSet#getFilterHash()
  633. */
  634. public Hashtable getFilters() {
  635. // we need to build the hashtable dynamically
  636. return globalFilterSet.getFilterHash();
  637. }
  638. /**
  639. * Sets the base directory for the project, checking that
  640. * the given filename exists and is a directory.
  641. *
  642. * @param baseD The project base directory.
  643. * Must not be <code>null</code>.
  644. *
  645. * @exception BuildException if the directory if invalid
  646. */
  647. public void setBasedir(String baseD) throws BuildException {
  648. setBaseDir(new File(baseD));
  649. }
  650. /**
  651. * Sets the base directory for the project, checking that
  652. * the given file exists and is a directory.
  653. *
  654. * @param baseDir The project base directory.
  655. * Must not be <code>null</code>.
  656. * @exception BuildException if the specified file doesn't exist or
  657. * isn't a directory
  658. */
  659. public void setBaseDir(File baseDir) throws BuildException {
  660. baseDir = fileUtils.normalize(baseDir.getAbsolutePath());
  661. if (!baseDir.exists()) {
  662. throw new BuildException("Basedir " + baseDir.getAbsolutePath()
  663. + " does not exist");
  664. }
  665. if (!baseDir.isDirectory()) {
  666. throw new BuildException("Basedir " + baseDir.getAbsolutePath()
  667. + " is not a directory");
  668. }
  669. this.baseDir = baseDir;
  670. setPropertyInternal("basedir", this.baseDir.getPath());
  671. String msg = "Project base dir set to: " + this.baseDir;
  672. log(msg, MSG_VERBOSE);
  673. }
  674. /**
  675. * Returns the base directory of the project as a file object.
  676. *
  677. * @return the project base directory, or <code>null</code> if the
  678. * base directory has not been successfully set to a valid value.
  679. */
  680. public File getBaseDir() {
  681. if (baseDir == null) {
  682. try {
  683. setBasedir(".");
  684. } catch (BuildException ex) {
  685. ex.printStackTrace();
  686. }
  687. }
  688. return baseDir;
  689. }
  690. /**
  691. * Sets "keep-going" mode. In this mode ANT will try to execute
  692. * as many targets as possible. All targets that do not depend
  693. * on failed target(s) will be executed.
  694. * @param keepGoingMode "keep-going" mode
  695. * @since Ant 1.6
  696. */
  697. public void setKeepGoingMode(boolean keepGoingMode) {
  698. this.keepGoingMode = keepGoingMode;
  699. }
  700. /**
  701. * Returns the keep-going mode.
  702. * @return "keep-going" mode
  703. * @since Ant 1.6
  704. */
  705. public boolean isKeepGoingMode() {
  706. return this.keepGoingMode;
  707. }
  708. /**
  709. * Returns the version of Java this class is running under.
  710. * @return the version of Java as a String, e.g. "1.1"
  711. * @see org.apache.tools.ant.util.JavaEnvUtils#getJavaVersion
  712. * @deprecated use org.apache.tools.ant.util.JavaEnvUtils instead
  713. */
  714. public static String getJavaVersion() {
  715. return JavaEnvUtils.getJavaVersion();
  716. }
  717. /**
  718. * Sets the <code>ant.java.version</code> property and tests for
  719. * unsupported JVM versions. If the version is supported,
  720. * verbose log messages are generated to record the Java version
  721. * and operating system name.
  722. *
  723. * @exception BuildException if this Java version is not supported
  724. *
  725. * @see org.apache.tools.ant.util.JavaEnvUtils#getJavaVersion
  726. */
  727. public void setJavaVersionProperty() throws BuildException {
  728. String javaVersion = JavaEnvUtils.getJavaVersion();
  729. setPropertyInternal("ant.java.version", javaVersion);
  730. // sanity check
  731. if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_0)) {
  732. throw new BuildException("Ant cannot work on Java 1.0");
  733. }
  734. log("Detected Java version: " + javaVersion + " in: "
  735. + System.getProperty("java.home"), MSG_VERBOSE);
  736. log("Detected OS: " + System.getProperty("os.name"), MSG_VERBOSE);
  737. }
  738. /**
  739. * Adds all system properties which aren't already defined as
  740. * user properties to the project properties.
  741. */
  742. public void setSystemProperties() {
  743. Properties systemP = System.getProperties();
  744. Enumeration e = systemP.keys();
  745. while (e.hasMoreElements()) {
  746. Object name = e.nextElement();
  747. String value = systemP.get(name).toString();
  748. this.setPropertyInternal(name.toString(), value);
  749. }
  750. }
  751. /**
  752. * Adds a new task definition to the project.
  753. * Attempting to override an existing definition with an
  754. * equivalent one (i.e. with the same classname) results in
  755. * a verbose log message. Attempting to override an existing definition
  756. * with a different one results in a warning log message and
  757. * invalidates any tasks which have already been created with the
  758. * old definition.
  759. *
  760. * @param taskName The name of the task to add.
  761. * Must not be <code>null</code>.
  762. * @param taskClass The full name of the class implementing the task.
  763. * Must not be <code>null</code>.
  764. *
  765. * @exception BuildException if the class is unsuitable for being an Ant
  766. * task. An error level message is logged before
  767. * this exception is thrown.
  768. *
  769. * @see #checkTaskClass(Class)
  770. */
  771. public void addTaskDefinition(String taskName, Class taskClass)
  772. throws BuildException {
  773. ComponentHelper.getComponentHelper(this).addTaskDefinition(taskName,
  774. taskClass);
  775. }
  776. /**
  777. * Checks whether or not a class is suitable for serving as Ant task.
  778. * Ant task implementation classes must be public, concrete, and have
  779. * a no-arg constructor.
  780. *
  781. * @param taskClass The class to be checked.
  782. * Must not be <code>null</code>.
  783. *
  784. * @exception BuildException if the class is unsuitable for being an Ant
  785. * task. An error level message is logged before
  786. * this exception is thrown.
  787. */
  788. public void checkTaskClass(final Class taskClass) throws BuildException {
  789. ComponentHelper.getComponentHelper(this).checkTaskClass(taskClass);
  790. if (!Modifier.isPublic(taskClass.getModifiers())) {
  791. final String message = taskClass + " is not public";
  792. log(message, Project.MSG_ERR);
  793. throw new BuildException(message);
  794. }
  795. if (Modifier.isAbstract(taskClass.getModifiers())) {
  796. final String message = taskClass + " is abstract";
  797. log(message, Project.MSG_ERR);
  798. throw new BuildException(message);
  799. }
  800. try {
  801. taskClass.getConstructor(null);
  802. // don't have to check for public, since
  803. // getConstructor finds public constructors only.
  804. } catch (NoSuchMethodException e) {
  805. final String message = "No public no-arg constructor in "
  806. + taskClass;
  807. log(message, Project.MSG_ERR);
  808. throw new BuildException(message);
  809. } catch (LinkageError e) {
  810. String message = "Could not load " + taskClass + ": " + e;
  811. log(message, Project.MSG_ERR);
  812. throw new BuildException(message, e);
  813. }
  814. if (!Task.class.isAssignableFrom(taskClass)) {
  815. TaskAdapter.checkTaskClass(taskClass, this);
  816. }
  817. }
  818. /**
  819. * Returns the current task definition hashtable. The returned hashtable is
  820. * "live" and so should not be modified.
  821. *
  822. * @return a map of from task name to implementing class
  823. * (String to Class).
  824. */
  825. public Hashtable getTaskDefinitions() {
  826. return ComponentHelper.getComponentHelper(this).getTaskDefinitions();
  827. }
  828. /**
  829. * Adds a new datatype definition.
  830. * Attempting to override an existing definition with an
  831. * equivalent one (i.e. with the same classname) results in
  832. * a verbose log message. Attempting to override an existing definition
  833. * with a different one results in a warning log message, but the
  834. * definition is changed.
  835. *
  836. * @param typeName The name of the datatype.
  837. * Must not be <code>null</code>.
  838. * @param typeClass The full name of the class implementing the datatype.
  839. * Must not be <code>null</code>.
  840. */
  841. public void addDataTypeDefinition(String typeName, Class typeClass) {
  842. ComponentHelper.getComponentHelper(this).addDataTypeDefinition(typeName,
  843. typeClass);
  844. }
  845. /**
  846. * Returns the current datatype definition hashtable. The returned
  847. * hashtable is "live" and so should not be modified.
  848. *
  849. * @return a map of from datatype name to implementing class
  850. * (String to Class).
  851. */
  852. public Hashtable getDataTypeDefinitions() {
  853. return ComponentHelper.getComponentHelper(this).getDataTypeDefinitions();
  854. }
  855. /**
  856. * Adds a <em>new</em> target to the project.
  857. *
  858. * @param target The target to be added to the project.
  859. * Must not be <code>null</code>.
  860. *
  861. * @exception BuildException if the target already exists in the project
  862. *
  863. * @see Project#addOrReplaceTarget
  864. */
  865. public void addTarget(Target target) throws BuildException {
  866. addTarget(target.getName(), target);
  867. }
  868. /**
  869. * Adds a <em>new</em> target to the project.
  870. *
  871. * @param targetName The name to use for the target.
  872. * Must not be <code>null</code>.
  873. * @param target The target to be added to the project.
  874. * Must not be <code>null</code>.
  875. *
  876. * @exception BuildException if the target already exists in the project
  877. *
  878. * @see Project#addOrReplaceTarget
  879. */
  880. public void addTarget(String targetName, Target target)
  881. throws BuildException {
  882. if (targets.get(targetName) != null) {
  883. throw new BuildException("Duplicate target: `" + targetName + "'");
  884. }
  885. addOrReplaceTarget(targetName, target);
  886. }
  887. /**
  888. * Adds a target to the project, or replaces one with the same
  889. * name.
  890. *
  891. * @param target The target to be added or replaced in the project.
  892. * Must not be <code>null</code>.
  893. */
  894. public void addOrReplaceTarget(Target target) {
  895. addOrReplaceTarget(target.getName(), target);
  896. }
  897. /**
  898. * Adds a target to the project, or replaces one with the same
  899. * name.
  900. *
  901. * @param targetName The name to use for the target.
  902. * Must not be <code>null</code>.
  903. * @param target The target to be added or replaced in the project.
  904. * Must not be <code>null</code>.
  905. */
  906. public void addOrReplaceTarget(String targetName, Target target) {
  907. String msg = " +Target: " + targetName;
  908. log(msg, MSG_DEBUG);
  909. target.setProject(this);
  910. targets.put(targetName, target);
  911. }
  912. /**
  913. * Returns the hashtable of targets. The returned hashtable
  914. * is "live" and so should not be modified.
  915. * @return a map from name to target (String to Target).
  916. */
  917. public Hashtable getTargets() {
  918. return targets;
  919. }
  920. /**
  921. * Creates a new instance of a task, adding it to a list of
  922. * created tasks for later invalidation. This causes all tasks
  923. * to be remembered until the containing project is removed
  924. * @param taskType The name of the task to create an instance of.
  925. * Must not be <code>null</code>.
  926. *
  927. * @return an instance of the specified task, or <code>null</code> if
  928. * the task name is not recognised.
  929. *
  930. * @exception BuildException if the task name is recognised but task
  931. * creation fails.
  932. */
  933. public Task createTask(String taskType) throws BuildException {
  934. return ComponentHelper.getComponentHelper(this).createTask(taskType);
  935. }
  936. /**
  937. * Creates a new instance of a data type.
  938. *
  939. * @param typeName The name of the data type to create an instance of.
  940. * Must not be <code>null</code>.
  941. *
  942. * @return an instance of the specified data type, or <code>null</code> if
  943. * the data type name is not recognised.
  944. *
  945. * @exception BuildException if the data type name is recognised but
  946. * instance creation fails.
  947. */
  948. public Object createDataType(String typeName) throws BuildException {
  949. return ComponentHelper.getComponentHelper(this).createDataType(typeName);
  950. }
  951. /**
  952. * Execute the specified sequence of targets, and the targets
  953. * they depend on.
  954. *
  955. * @param targetNames A vector of target name strings to execute.
  956. * Must not be <code>null</code>.
  957. *
  958. * @exception BuildException if the build failed
  959. */
  960. public void executeTargets(Vector targetNames) throws BuildException {
  961. BuildException thrownException = null;
  962. for (int i = 0; i < targetNames.size(); i++) {
  963. try {
  964. executeTarget((String) targetNames.elementAt(i));
  965. } catch (BuildException ex) {
  966. if (!(keepGoingMode)) {
  967. throw ex; // Throw further
  968. }
  969. thrownException = ex;
  970. }
  971. }
  972. if (thrownException != null) {
  973. throw thrownException;
  974. }
  975. }
  976. /**
  977. * Demultiplexes output so that each task receives the appropriate
  978. * messages. If the current thread is not currently executing a task,
  979. * the message is logged directly.
  980. *
  981. * @param output Message to handle. Should not be <code>null</code>.
  982. * @param isWarning Whether the text represents an warning (<code>true</code>)
  983. * or information (<code>false</code>).
  984. */
  985. public void demuxOutput(String output, boolean isWarning) {
  986. Task task = getThreadTask(Thread.currentThread());
  987. if (task == null) {
  988. log(output, isWarning ? MSG_WARN : MSG_INFO);
  989. } else {
  990. if (isWarning) {
  991. task.handleErrorOutput(output);
  992. } else {
  993. task.handleOutput(output);
  994. }
  995. }
  996. }
  997. /**
  998. * Read data from the default input stream. If no default has been
  999. * specified, System.in is used.
  1000. *
  1001. * @param buffer the buffer into which data is to be read.
  1002. * @param offset the offset into the buffer at which data is stored.
  1003. * @param length the amount of data to read
  1004. *
  1005. * @return the number of bytes read
  1006. *
  1007. * @exception IOException if the data cannot be read
  1008. * @since Ant 1.6
  1009. */
  1010. public int defaultInput(byte[] buffer, int offset, int length)
  1011. throws IOException {
  1012. if (defaultInputStream != null) {
  1013. System.out.flush();
  1014. return defaultInputStream.read(buffer, offset, length);
  1015. } else {
  1016. throw new EOFException("No input provided for project");
  1017. }
  1018. }
  1019. /**
  1020. * Demux an input request to the correct task.
  1021. *
  1022. * @param buffer the buffer into which data is to be read.
  1023. * @param offset the offset into the buffer at which data is stored.
  1024. * @param length the amount of data to read
  1025. *
  1026. * @return the number of bytes read
  1027. *
  1028. * @exception IOException if the data cannot be read
  1029. * @since Ant 1.6
  1030. */
  1031. public int demuxInput(byte[] buffer, int offset, int length)
  1032. throws IOException {
  1033. Task task = getThreadTask(Thread.currentThread());
  1034. if (task == null) {
  1035. return defaultInput(buffer, offset, length);
  1036. } else {
  1037. return task.handleInput(buffer, offset, length);
  1038. }
  1039. }
  1040. /**
  1041. * Demultiplexes flush operation so that each task receives the appropriate
  1042. * messages. If the current thread is not currently executing a task,
  1043. * the message is logged directly.
  1044. *
  1045. * @since Ant 1.5.2
  1046. *
  1047. * @param output Message to handle. Should not be <code>null</code>.
  1048. * @param isError Whether the text represents an error (<code>true</code>)
  1049. * or information (<code>false</code>).
  1050. */
  1051. public void demuxFlush(String output, boolean isError) {
  1052. Task task = getThreadTask(Thread.currentThread());
  1053. if (task == null) {
  1054. fireMessageLogged(this, output, isError ? MSG_ERR : MSG_INFO);
  1055. } else {
  1056. if (isError) {
  1057. task.handleErrorFlush(output);
  1058. } else {
  1059. task.handleFlush(output);
  1060. }
  1061. }
  1062. }
  1063. /**
  1064. * Executes the specified target and any targets it depends on.
  1065. *
  1066. * @param targetName The name of the target to execute.
  1067. * Must not be <code>null</code>.
  1068. *
  1069. * @exception BuildException if the build failed
  1070. */
  1071. public void executeTarget(String targetName) throws BuildException {
  1072. // sanity check ourselves, if we've been asked to build nothing
  1073. // then we should complain
  1074. if (targetName == null) {
  1075. String msg = "No target specified";
  1076. throw new BuildException(msg);
  1077. }
  1078. // Sort the dependency tree, and run everything from the
  1079. // beginning until we hit our targetName.
  1080. // Sorting checks if all the targets (and dependencies)
  1081. // exist, and if there is any cycle in the dependency
  1082. // graph.
  1083. Vector sortedTargets = topoSort(targetName, targets);
  1084. Set succeededTargets = new HashSet();
  1085. BuildException buildException = null; // first build exception
  1086. for (Enumeration iter = sortedTargets.elements();
  1087. iter.hasMoreElements();) {
  1088. Target curtarget = (Target) iter.nextElement();
  1089. boolean canExecute = true;
  1090. for (Enumeration depIter = curtarget.getDependencies();
  1091. depIter.hasMoreElements();) {
  1092. String dependencyName = ((String) depIter.nextElement());
  1093. if (!succeededTargets.contains(dependencyName)) {
  1094. canExecute = false;
  1095. log(curtarget,
  1096. "Cannot execute '" + curtarget.getName() + "' - '"
  1097. + dependencyName + "' failed or was not executed.",
  1098. MSG_ERR);
  1099. break;
  1100. }
  1101. }
  1102. if (canExecute) {
  1103. Throwable thrownException = null;
  1104. try {
  1105. curtarget.performTasks();
  1106. succeededTargets.add(curtarget.getName());
  1107. } catch (RuntimeException ex) {
  1108. if (!(keepGoingMode)) {
  1109. throw ex; // throw further
  1110. }
  1111. thrownException = ex;
  1112. } catch (Throwable ex) {
  1113. if (!(keepGoingMode)) {
  1114. throw new BuildException(ex);
  1115. }
  1116. thrownException = ex;
  1117. }
  1118. if (thrownException != null) {
  1119. if (thrownException instanceof BuildException) {
  1120. log(curtarget,
  1121. "Target '" + curtarget.getName()
  1122. + "' failed with message '"
  1123. + thrownException.getMessage() + "'.", MSG_ERR);
  1124. // only the first build exception is reported
  1125. if (buildException == null) {
  1126. buildException = (BuildException) thrownException;
  1127. }
  1128. } else {
  1129. log(curtarget,
  1130. "Target '" + curtarget.getName()
  1131. + "' failed with message '"
  1132. + thrownException.getMessage() + "'.", MSG_ERR);
  1133. thrownException.printStackTrace(System.err);
  1134. if (buildException == null) {
  1135. buildException =
  1136. new BuildException(thrownException);
  1137. }
  1138. }
  1139. }
  1140. }
  1141. if (curtarget.getName().equals(targetName)) { // old exit condition
  1142. break;
  1143. }
  1144. }
  1145. if (buildException != null) {
  1146. throw buildException;
  1147. }
  1148. }
  1149. /**
  1150. * Returns the canonical form of a filename.
  1151. * <p>
  1152. * If the specified file name is relative it is resolved
  1153. * with respect to the given root directory.
  1154. *
  1155. * @param fileName The name of the file to resolve.
  1156. * Must not be <code>null</code>.
  1157. *
  1158. * @param rootDir The directory to resolve relative file names with
  1159. * respect to. May be <code>null</code>, in which case
  1160. * the current directory is used.
  1161. *
  1162. * @return the resolved File.
  1163. *
  1164. * @deprecated
  1165. */
  1166. public File resolveFile(String fileName, File rootDir) {
  1167. return fileUtils.resolveFile(rootDir, fileName);
  1168. }
  1169. /**
  1170. * Returns the canonical form of a filename.
  1171. * <p>
  1172. * If the specified file name is relative it is resolved
  1173. * with respect to the project's base directory.
  1174. *
  1175. * @param fileName The name of the file to resolve.
  1176. * Must not be <code>null</code>.
  1177. *
  1178. * @return the resolved File.
  1179. *
  1180. */
  1181. public File resolveFile(String fileName) {
  1182. return fileUtils.resolveFile(baseDir, fileName);
  1183. }
  1184. /**
  1185. * Translates a path into its native (platform specific) format.
  1186. * <p>
  1187. * This method uses PathTokenizer to separate the input path
  1188. * into its components. This handles DOS style paths in a relatively
  1189. * sensible way. The file separators are then converted to their platform
  1190. * specific versions.
  1191. *
  1192. * @param toProcess The path to be translated.
  1193. * May be <code>null</code>.
  1194. *
  1195. * @return the native version of the specified path or
  1196. * an empty string if the path is <code>null</code> or empty.
  1197. *
  1198. * @see PathTokenizer
  1199. */
  1200. public static String translatePath(String toProcess) {
  1201. if (toProcess == null || toProcess.length() == 0) {
  1202. return "";
  1203. }
  1204. StringBuffer path = new StringBuffer(toProcess.length() + 50);
  1205. PathTokenizer tokenizer = new PathTokenizer(toProcess);
  1206. while (tokenizer.hasMoreTokens()) {
  1207. String pathComponent = tokenizer.nextToken();
  1208. pathComponent = pathComponent.replace('/', File.separatorChar);
  1209. pathComponent = pathComponent.replace('\\', File.separatorChar);
  1210. if (path.length() != 0) {
  1211. path.append(File.pathSeparatorChar);
  1212. }
  1213. path.append(pathComponent);
  1214. }
  1215. return path.toString();
  1216. }
  1217. /**
  1218. * Convenience method to copy a file from a source to a destination.
  1219. * No filtering is performed.
  1220. *
  1221. * @param sourceFile Name of file to copy from.
  1222. * Must not be <code>null</code>.
  1223. * @param destFile Name of file to copy to.
  1224. * Must not be <code>null</code>.
  1225. *
  1226. * @exception IOException if the copying fails
  1227. *
  1228. * @deprecated
  1229. */
  1230. public void copyFile(String sourceFile, String destFile)
  1231. throws IOException {
  1232. fileUtils.copyFile(sourceFile, destFile);
  1233. }
  1234. /**
  1235. * Convenience method to copy a file from a source to a destination
  1236. * specifying if token filtering should be used.
  1237. *
  1238. * @param sourceFile Name of file to copy from.
  1239. * Must not be <code>null</code>.
  1240. * @param destFile Name of file to copy to.
  1241. * Must not be <code>null</code>.
  1242. * @param filtering Whether or not token filtering should be used during
  1243. * the copy.
  1244. *
  1245. * @exception IOException if the copying fails
  1246. *
  1247. * @deprecated
  1248. */
  1249. public void copyFile(String sourceFile, String destFile, boolean filtering)
  1250. throws IOException {
  1251. fileUtils.copyFile(sourceFile, destFile,
  1252. filtering ? globalFilters : null);
  1253. }
  1254. /**
  1255. * Convenience method to copy a file from a source to a
  1256. * destination specifying if token filtering should be used and if
  1257. * source files may overwrite newer destination files.
  1258. *
  1259. * @param sourceFile Name of file to copy from.
  1260. * Must not be <code>null</code>.
  1261. * @param destFile Name of file to copy to.
  1262. * Must not be <code>null</code>.
  1263. * @param filtering Whether or not token filtering should be used during
  1264. * the copy.
  1265. * @param overwrite Whether or not the destination file should be
  1266. * overwritten if it already exists.
  1267. *
  1268. * @exception IOException if the copying fails
  1269. *
  1270. * @deprecated
  1271. */
  1272. public void copyFile(String sourceFile, String destFile, boolean filtering,
  1273. boolean overwrite) throws IOException {
  1274. fileUtils.copyFile(sourceFile, destFile,
  1275. filtering ? globalFilters : null, overwrite);
  1276. }
  1277. /**
  1278. * Convenience method to copy a file from a source to a
  1279. * destination specifying if token filtering should be used, if
  1280. * source files may overwrite newer destination files, and if the
  1281. * last modified time of the resulting file should be set to
  1282. * that of the source file.
  1283. *
  1284. * @param sourceFile Name of file to copy from.
  1285. * Must not be <code>null</code>.
  1286. * @param destFile Name of file to copy to.
  1287. * Must not be <code>null</code>.
  1288. * @param filtering Whether or not token filtering should be used during
  1289. * the copy.
  1290. * @param overwrite Whether or not the destination file should be
  1291. * overwritten if it already exists.
  1292. * @param preserveLastModified Whether or not the last modified time of
  1293. * the resulting file should be set to that
  1294. * of the source file.
  1295. *
  1296. * @exception IOException if the copying fails
  1297. *
  1298. * @deprecated
  1299. */
  1300. public void copyFile(String sourceFile, String destFile, boolean filtering,
  1301. boolean overwrite, boolean preserveLastModified)
  1302. throws IOException {
  1303. fileUtils.copyFile(sourceFile, destFile,
  1304. filtering ? globalFilters : null, overwrite, preserveLastModified);
  1305. }
  1306. /**
  1307. * Convenience method to copy a file from a source to a destination.
  1308. * No filtering is performed.
  1309. *
  1310. * @param sourceFile File to copy from.
  1311. * Must not be <code>null</code>.
  1312. * @param destFile File to copy to.
  1313. * Must not be <code>null</code>.
  1314. *
  1315. * @exception IOException if the copying fails
  1316. *
  1317. * @deprecated
  1318. */
  1319. public void copyFile(File sourceFile, File destFile) throws IOException {
  1320. fileUtils.copyFile(sourceFile, destFile);
  1321. }
  1322. /**
  1323. * Convenience method to copy a file from a source to a destination
  1324. * specifying if token filtering should be used.
  1325. *
  1326. * @param sourceFile File to copy from.
  1327. * Must not be <code>null</code>.
  1328. * @param destFile File to copy to.
  1329. * Must not be <code>null</code>.
  1330. * @param filtering Whether or not token filtering should be used during
  1331. * the copy.
  1332. *
  1333. * @exception IOException if the copying fails
  1334. *
  1335. * @deprecated
  1336. */
  1337. public void copyFile(File sourceFile, File destFile, boolean filtering)
  1338. throws IOException {
  1339. fileUtils.copyFile(sourceFile, destFile,
  1340. filtering ? globalFilters : null);
  1341. }
  1342. /**
  1343. * Convenience method to copy a file from a source to a
  1344. * destination specifying if token filtering should be used and if
  1345. * source files may overwrite newer destination files.
  1346. *
  1347. * @param sourceFile File to copy from.
  1348. * Must not be <code>null</code>.
  1349. * @param destFile File to copy to.
  1350. * Must not be <code>null</code>.
  1351. * @param filtering Whether or not token filtering should be used during
  1352. * the copy.
  1353. * @param overwrite Whether or not the destination file should be
  1354. * overwritten if it already exists.
  1355. *
  1356. * @exception IOException if the file cannot be copied.
  1357. *
  1358. * @deprecated
  1359. */
  1360. public void copyFile(File sourceFile, File destFile, boolean filtering,
  1361. boolean overwrite) throws IOException {
  1362. fileUtils.copyFile(sourceFile, destFile,
  1363. filtering ? globalFilters : null, overwrite);
  1364. }
  1365. /**
  1366. * Convenience method to copy a file from a source to a
  1367. * destination specifying if token filtering should be used, if
  1368. * source files may overwrite newer destination files, and if the
  1369. * last modified time of the resulting file should be set to
  1370. * that of the source file.
  1371. *
  1372. * @param sourceFile File to copy from.
  1373. * Must not be <code>null</code>.
  1374. * @param destFile File to copy to.
  1375. * Must not be <code>null</code>.
  1376. * @param filtering Whether or not token filtering should be used during
  1377. * the copy.
  1378. * @param overwrite Whether or not the destination file should be
  1379. * overwritten if it already exists.
  1380. * @param preserveLastModified Whether or not the last modified time of
  1381. * the resulting file should be set to that
  1382. * of the source file.
  1383. *
  1384. * @exception IOException if the file cannot be copied.
  1385. *
  1386. * @deprecated
  1387. */
  1388. public void copyFile(File sourceFile, File destFile, boolean filtering,
  1389. boolean overwrite, boolean preserveLastModified)
  1390. throws IOException {
  1391. fileUtils.copyFile(sourceFile, destFile,
  1392. filtering ? globalFilters : null, overwrite, preserveLastModified);
  1393. }
  1394. /**
  1395. * Calls File.setLastModified(long time) on Java above 1.1, and logs
  1396. * a warning on Java 1.1.
  1397. *
  1398. * @param file The file to set the last modified time on.
  1399. * Must not be <code>null</code>.
  1400. *
  1401. * @param time the required modification time.
  1402. *
  1403. * @deprecated
  1404. *
  1405. * @exception BuildException if the last modified time cannot be set
  1406. * despite running on a platform with a version
  1407. * above 1.1.
  1408. */
  1409. public void setFileLastModified(File file, long time)
  1410. throws BuildException {
  1411. if (JavaEnvUtils.isJavaVersion(JavaEnvUtils.JAVA_1_1)) {
  1412. log("Cannot change the modification time of " + file
  1413. + " in JDK 1.1", Project.MSG_WARN);
  1414. return;
  1415. }
  1416. fileUtils.setFileLastModified(file, time);
  1417. log("Setting modification time for " + file, MSG_VERBOSE);
  1418. }
  1419. /**
  1420. * Returns the boolean equivalent of a string, which is considered
  1421. * <code>true</code> if either <code>"on"</code>, <code>"true"</code>,
  1422. * or <code>"yes"</code> is found, ignoring case.
  1423. *
  1424. * @param s The string to convert to a boolean value.
  1425. *
  1426. * @return <code>true</code> if the given string is <code>"on"</code>,
  1427. * <code>"true"</code> or <code>"yes"</code>, or
  1428. * <code>false</code> otherwise.
  1429. */
  1430. public static boolean toBoolean(String s) {
  1431. return ("on".equalsIgnoreCase(s)
  1432. || "true".equalsIgnoreCase(s)
  1433. || "yes".equalsIgnoreCase(s));
  1434. }
  1435. /**
  1436. * Topologically sorts a set of targets.
  1437. *
  1438. * @param root The name of the root target. The sort is created in such
  1439. * a way that the sequence of Targets up to the root
  1440. * target is the minimum possible such sequence.
  1441. * Must not be <code>null</code>.
  1442. * @param targets A map of names to targets (String to Target).
  1443. * Must not be <code>null</code>.
  1444. * @return a vector of Target objects in sorted order.
  1445. * @exception BuildException if there is a cyclic dependency among the
  1446. * targets, or if a named target does not exist.
  1447. */
  1448. public final Vector topoSort(String root, Hashtable targets)
  1449. throws BuildException {
  1450. Vector ret = new Vector();
  1451. Hashtable state = new Hashtable();
  1452. Stack visiting = new Stack();
  1453. // We first run a DFS based sort using the root as the starting node.
  1454. // This creates the minimum sequence of Targets to the root node.
  1455. // We then do a sort on any remaining unVISITED targets.
  1456. // This is unnecessary for doing our build, but it catches
  1457. // circular dependencies or missing Targets on the entire
  1458. // dependency tree, not just on the Targets that depend on the
  1459. // build Target.
  1460. tsort(root, targets, state, visiting, ret);
  1461. log("Build sequence for target `" + root + "' is " + ret, MSG_VERBOSE);
  1462. for (Enumeration en = targets.keys(); en.hasMoreElements();) {
  1463. String curTarget = (String) en.nextElement();
  1464. String st = (String) state.get(curTarget);
  1465. if (st == null) {
  1466. tsort(curTarget, targets, state, visiting, ret);
  1467. } else if (st == VISITING) {
  1468. throw new RuntimeException("Unexpected node in visiting state: "
  1469. + curTarget);
  1470. }
  1471. }
  1472. log("Complete build sequence is " + ret, MSG_VERBOSE);
  1473. return ret;
  1474. }
  1475. /**
  1476. * Performs a single step in a recursive depth-first-search traversal of
  1477. * the target dependency tree.
  1478. * <p>
  1479. * The current target is first set to the "visiting" state, and pushed
  1480. * onto the "visiting" stack.
  1481. * <p>
  1482. * An exception is then thrown if any child of the current node is in the
  1483. * visiting state, as that implies a circular dependency. The exception
  1484. * contains details of the cycle, using elements of the "visiting" stack.
  1485. * <p>
  1486. * If any child has not already been "visited", this method is called
  1487. * recursively on it.
  1488. * <p>
  1489. * The current target is then added to the ordered list of targets. Note
  1490. * that this is performed after the children have been visited in order
  1491. * to get the correct order. The current target is set to the "visited"
  1492. * state.
  1493. * <p>
  1494. * By the time this method returns, the ordered list contains the sequence
  1495. * of targets up to and including the current target.
  1496. *
  1497. * @param root The current target to inspect.
  1498. * Must not be <code>null</code>.
  1499. * @param targets A mapping from names to targets (String to Target).
  1500. * Must not be <code>null</code>.
  1501. * @param state A mapping from target names to states
  1502. * (String to String).
  1503. * The states in question are "VISITING" and "VISITED".
  1504. * Must not be <code>null</code>.
  1505. * @param visiting A stack of targets which are currently being visited.
  1506. * Must not be <code>null</code>.
  1507. * @param ret The list to add target names to. This will end up
  1508. * containing the complete list of dependencies in
  1509. * dependency order.
  1510. * Must not be <code>null</code>.
  1511. *
  1512. * @exception BuildException if a non-existent target is specified or if
  1513. * a circular dependency is detected.
  1514. */
  1515. private final void tsort(String root, Hashtable targets,
  1516. Hashtable state, Stack visiting,
  1517. Vector ret)
  1518. throws BuildException {
  1519. state.put(root, VISITING);
  1520. visiting.push(root);
  1521. Target target = (Target) targets.get(root);
  1522. // Make sure we exist
  1523. if (target == null) {
  1524. StringBuffer sb = new StringBuffer("Target `");
  1525. sb.append(root);
  1526. sb.append("' does not exist in this project. ");
  1527. visiting.pop();
  1528. if (!visiting.empty()) {
  1529. String parent = (String) visiting.peek();
  1530. sb.append("It is used from target `");
  1531. sb.append(parent);
  1532. sb.append("'.");
  1533. }
  1534. throw new BuildException(new String(sb));
  1535. }
  1536. for (Enumeration en = target.getDependencies(); en.hasMoreElements();) {
  1537. String cur = (String) en.nextElement();
  1538. String m = (String) state.get(cur);
  1539. if (m == null) {
  1540. // Not been visited
  1541. tsort(cur, targets, state, visiting, ret);
  1542. } else if (m == VISITING) {
  1543. // Currently visiting this node, so have a cycle
  1544. throw makeCircularException(cur, visiting);
  1545. }
  1546. }
  1547. String p = (String) visiting.pop();
  1548. if (root != p) {
  1549. throw new RuntimeException("Unexpected internal error: expected to "
  1550. + "pop " + root + " but got " + p);
  1551. }
  1552. state.put(root, VISITED);
  1553. ret.addElement(target);
  1554. }
  1555. /**
  1556. * Builds an appropriate exception detailing a specified circular
  1557. * dependency.
  1558. *
  1559. * @param end The dependency to stop at. Must not be <code>null</code>.
  1560. * @param stk A stack of dependencies. Must not be <code>null</code>.
  1561. *
  1562. * @return a BuildException detailing the specified circular dependency.
  1563. */
  1564. private static BuildException makeCircularException(String end, Stack stk) {
  1565. StringBuffer sb = new StringBuffer("Circular dependency: ");
  1566. sb.append(end);
  1567. String c;
  1568. do {
  1569. c = (String) stk.pop();
  1570. sb.append(" <- ");
  1571. sb.append(c);
  1572. } while (!c.equals(end));
  1573. return new BuildException(new String(sb));
  1574. }
  1575. /**
  1576. * Adds a reference to the project.
  1577. *
  1578. * @param name The name of the reference. Must not be <code>null</code>.
  1579. * @param value The value of the reference. Must not be <code>null</code>.
  1580. */
  1581. public void addReference(String name, Object value) {
  1582. synchronized (references) {
  1583. Object old = ((AntRefTable) references).getReal(name);
  1584. if (old == value) {
  1585. // no warning, this is not changing anything
  1586. return;
  1587. }
  1588. if (old != null && !(old instanceof UnknownElement)) {
  1589. log("Overriding previous definition of reference to " + name,
  1590. MSG_WARN);
  1591. }
  1592. log("Adding reference: " + name, MSG_DEBUG);
  1593. references.put(name, value);
  1594. }
  1595. }
  1596. /**
  1597. * Returns a map of the references in the project (String to Object).
  1598. * The returned hashtable is "live" and so must not be modified.
  1599. *
  1600. * @return a map of the references in the project (String to Object).
  1601. */
  1602. public Hashtable getReferences() {
  1603. return references;
  1604. }
  1605. /**
  1606. * Looks up a reference by its key (ID).
  1607. *
  1608. * @param key The key for the desired reference.
  1609. * Must not be <code>null</code>.
  1610. *
  1611. * @return the reference with the specified ID, or <code>null</code> if
  1612. * there is no such reference in the project.
  1613. */
  1614. public Object getReference(String key) {
  1615. return references.get(key);
  1616. }
  1617. /**
  1618. * Returns a description of the type of the given element, with
  1619. * special handling for instances of tasks and data types.
  1620. * <p>
  1621. * This is useful for logging purposes.
  1622. *
  1623. * @param element The element to describe.
  1624. * Must not be <code>null</code>.
  1625. *
  1626. * @return a description of the element type
  1627. *
  1628. * @since 1.95, Ant 1.5
  1629. */
  1630. public String getElementName(Object element) {
  1631. return ComponentHelper.getComponentHelper(this).getElementName(element);
  1632. }
  1633. /**
  1634. * Sends a "build started" event to the build listeners for this project.
  1635. */
  1636. public void fireBuildStarted() {
  1637. BuildEvent event = new BuildEvent(this);
  1638. Iterator iter = listeners.iterator();
  1639. while (iter.hasNext()) {
  1640. BuildListener listener = (BuildListener) iter.next();
  1641. listener.buildStarted(event);
  1642. }
  1643. }
  1644. /**
  1645. * Sends a "build finished" event to the build listeners for this project.
  1646. * @param exception an exception indicating a reason for a build
  1647. * failure. May be <code>null</code>, indicating
  1648. * a successful build.
  1649. */
  1650. public void fireBuildFinished(Throwable exception) {
  1651. BuildEvent event = new BuildEvent(this);
  1652. event.setException(exception);
  1653. Iterator iter = listeners.iterator();
  1654. while (iter.hasNext()) {
  1655. BuildListener listener = (BuildListener) iter.next();
  1656. listener.buildFinished(event);
  1657. }
  1658. }
  1659. /**
  1660. * Sends a "subbuild started" event to the build listeners for
  1661. * this project.
  1662. *
  1663. * @since Ant 1.6.2
  1664. */
  1665. public void fireSubBuildStarted() {
  1666. BuildEvent event = new BuildEvent(this);
  1667. Iterator iter = listeners.iterator();
  1668. while (iter.hasNext()) {
  1669. Object listener = iter.next();
  1670. if (listener instanceof SubBuildListener) {
  1671. ((SubBuildListener) listener).subBuildStarted(event);
  1672. }
  1673. }
  1674. }
  1675. /**
  1676. * Sends a "subbuild finished" event to the build listeners for
  1677. * this project.
  1678. * @param exception an exception indicating a reason for a build
  1679. * failure. May be <code>null</code>, indicating
  1680. * a successful build.
  1681. *
  1682. * @since Ant 1.6.2
  1683. */
  1684. public void fireSubBuildFinished(Throwable exception) {
  1685. BuildEvent event = new BuildEvent(this);
  1686. event.setException(exception);
  1687. Iterator iter = listeners.iterator();
  1688. while (iter.hasNext()) {
  1689. Object listener = iter.next();
  1690. if (listener instanceof SubBuildListener) {
  1691. ((SubBuildListener) listener).subBuildFinished(event);
  1692. }
  1693. }
  1694. }
  1695. /**
  1696. * Sends a "target started" event to the build listeners for this project.
  1697. *
  1698. * @param target The target which is starting to build.
  1699. * Must not be <code>null</code>.
  1700. */
  1701. protected void fireTargetStarted(Target target) {
  1702. BuildEvent event = new BuildEvent(target);
  1703. Iterator iter = listeners.iterator();
  1704. while (iter.hasNext()) {
  1705. BuildListener listener = (BuildListener) iter.next();
  1706. listener.targetStarted(event);
  1707. }
  1708. }
  1709. /**
  1710. * Sends a "target finished" event to the build listeners for this
  1711. * project.
  1712. *
  1713. * @param target The target which has finished building.
  1714. * Must not be <code>null</code>.
  1715. * @param exception an exception indicating a reason for a build
  1716. * failure. May be <code>null</code>, indicating
  1717. * a successful build.
  1718. */
  1719. protected void fireTargetFinished(Target target, Throwable exception) {
  1720. BuildEvent event = new BuildEvent(target);
  1721. event.setException(exception);
  1722. Iterator iter = listeners.iterator();
  1723. while (iter.hasNext()) {
  1724. BuildListener listener = (BuildListener) iter.next();
  1725. listener.targetFinished(event);
  1726. }
  1727. }
  1728. /**
  1729. * Sends a "task started" event to the build listeners for this project.
  1730. *
  1731. * @param task The target which is starting to execute.
  1732. * Must not be <code>null</code>.
  1733. */
  1734. protected void fireTaskStarted(Task task) {
  1735. // register this as the current task on the current thread.
  1736. registerThreadTask(Thread.currentThread(), task);
  1737. BuildEvent event = new BuildEvent(task);
  1738. Iterator iter = listeners.iterator();
  1739. while (iter.hasNext()) {
  1740. BuildListener listener = (BuildListener) iter.next();
  1741. listener.taskStarted(event);
  1742. }
  1743. }
  1744. /**
  1745. * Sends a "task finished" event to the build listeners for this
  1746. * project.
  1747. *
  1748. * @param task The task which has finished executing.
  1749. * Must not be <code>null</code>.
  1750. * @param exception an exception indicating a reason for a build
  1751. * failure. May be <code>null</code>, indicating
  1752. * a successful build.
  1753. */
  1754. protected void fireTaskFinished(Task task, Throwable exception) {
  1755. registerThreadTask(Thread.currentThread(), null);
  1756. System.out.flush();
  1757. System.err.flush();
  1758. BuildEvent event = new BuildEvent(task);
  1759. event.setException(exception);
  1760. Iterator iter = listeners.iterator();
  1761. while (iter.hasNext()) {
  1762. BuildListener listener = (BuildListener) iter.next();
  1763. listener.taskFinished(event);
  1764. }
  1765. }
  1766. /**
  1767. * Sends a "message logged" event to the build listeners for this project.
  1768. *
  1769. * @param event The event to send. This should be built up with the
  1770. * appropriate task/target/project by the caller, so that
  1771. * this method can set the message and priority, then send
  1772. * the event. Must not be <code>null</code>.
  1773. * @param message The message to send. Should not be <code>null</code>.
  1774. * @param priority The priority of the message.
  1775. */
  1776. private void fireMessageLoggedEvent(BuildEvent event, String message,
  1777. int priority) {
  1778. if (message.endsWith(StringUtils.LINE_SEP)) {
  1779. int endIndex = message.length() - StringUtils.LINE_SEP.length();
  1780. event.setMessage(message.substring(0, endIndex), priority);
  1781. } else {
  1782. event.setMessage(message, priority);
  1783. }
  1784. synchronized (this) {
  1785. if (loggingMessage) {
  1786. throw new BuildException("Listener attempted to access "
  1787. + (priority == MSG_ERR ? "System.err" : "System.out")
  1788. + " - infinite loop terminated");
  1789. }
  1790. try {
  1791. loggingMessage = true;
  1792. Iterator iter = listeners.iterator();
  1793. while (iter.hasNext()) {
  1794. BuildListener listener = (BuildListener) iter.next();
  1795. listener.messageLogged(event);
  1796. }
  1797. } finally {
  1798. loggingMessage = false;
  1799. }
  1800. }
  1801. }
  1802. /**
  1803. * Sends a "message logged" project level event to the build listeners for
  1804. * this project.
  1805. *
  1806. * @param project The project generating the event.
  1807. * Should not be <code>null</code>.
  1808. * @param message The message to send. Should not be <code>null</code>.
  1809. * @param priority The priority of the message.
  1810. */
  1811. protected void fireMessageLogged(Project project, String message,
  1812. int priority) {
  1813. BuildEvent event = new BuildEvent(project);
  1814. fireMessageLoggedEvent(event, message, priority);
  1815. }
  1816. /**
  1817. * Sends a "message logged" target level event to the build listeners for
  1818. * this project.
  1819. *
  1820. * @param target The target generating the event.
  1821. * Must not be <code>null</code>.
  1822. * @param message The message to send. Should not be <code>null</code>.
  1823. * @param priority The priority of the message.
  1824. */
  1825. protected void fireMessageLogged(Target target, String message,
  1826. int priority) {
  1827. BuildEvent event = new BuildEvent(target);
  1828. fireMessageLoggedEvent(event, message, priority);
  1829. }
  1830. /**
  1831. * Sends a "message logged" task level event to the build listeners for
  1832. * this project.
  1833. *
  1834. * @param task The task generating the event.
  1835. * Must not be <code>null</code>.
  1836. * @param message The message to send. Should not be <code>null</code>.
  1837. * @param priority The priority of the message.
  1838. */
  1839. protected void fireMessageLogged(Task task, String message, int priority) {
  1840. BuildEvent event = new BuildEvent(task);
  1841. fireMessageLoggedEvent(event, message, priority);
  1842. }
  1843. /**
  1844. * Register a task as the current task for a thread.
  1845. * If the task is null, the thread's entry is removed.
  1846. *
  1847. * @param thread the thread on which the task is registered.
  1848. * @param task the task to be registered.
  1849. * @since Ant 1.5
  1850. */
  1851. public synchronized void registerThreadTask(Thread thread, Task task) {
  1852. if (task != null) {
  1853. threadTasks.put(thread, task);
  1854. threadGroupTasks.put(thread.getThreadGroup(), task);
  1855. } else {
  1856. threadTasks.remove(thread);
  1857. threadGroupTasks.remove(thread.getThreadGroup());
  1858. }
  1859. }
  1860. /**
  1861. * Get the current task associated with a thread, if any
  1862. *
  1863. * @param thread the thread for which the task is required.
  1864. * @return the task which is currently registered for the given thread or
  1865. * null if no task is registered.
  1866. */
  1867. public Task getThreadTask(Thread thread) {
  1868. Task task = (Task) threadTasks.get(thread);
  1869. if (task == null) {
  1870. ThreadGroup group = thread.getThreadGroup();
  1871. while (task == null && group != null) {
  1872. task = (Task) threadGroupTasks.get(group);
  1873. group = group.getParent();
  1874. }
  1875. }
  1876. return task;
  1877. }
  1878. // Should move to a separate public class - and have API to add
  1879. // listeners, etc.
  1880. private static class AntRefTable extends Hashtable {
  1881. private Project project;
  1882. public AntRefTable(Project project) {
  1883. super();
  1884. this.project = project;
  1885. }
  1886. /** Returns the unmodified original object.
  1887. * This method should be called internally to
  1888. * get the 'real' object.
  1889. * The normal get method will do the replacement
  1890. * of UnknownElement ( this is similar with the JDNI
  1891. * refs behavior )
  1892. */
  1893. public Object getReal(Object key) {
  1894. return super.get(key);
  1895. }
  1896. /** Get method for the reference table.
  1897. * It can be used to hook dynamic references and to modify
  1898. * some references on the fly - for example for delayed
  1899. * evaluation.
  1900. *
  1901. * It is important to make sure that the processing that is
  1902. * done inside is not calling get indirectly.
  1903. *
  1904. * @param key
  1905. * @return
  1906. */
  1907. public Object get(Object key) {
  1908. //System.out.println("AntRefTable.get " + key);
  1909. Object o = super.get(key);
  1910. if (o instanceof UnknownElement) {
  1911. // Make sure that
  1912. UnknownElement ue = (UnknownElement) o;
  1913. ue.maybeConfigure();
  1914. o = ue.getRealThing();
  1915. }
  1916. return o;
  1917. }
  1918. }
  1919. /**
  1920. * Set a reference to this Project on the parameterized object.
  1921. * Need to set the project before other set/add elements
  1922. * are called
  1923. * @param obj the object to invoke setProject(this) on
  1924. */
  1925. public final void setProjectReference(final Object obj) {
  1926. if (obj instanceof ProjectComponent) {
  1927. ((ProjectComponent) obj).setProject(this);
  1928. return;
  1929. }
  1930. try {
  1931. Method method =
  1932. obj.getClass().getMethod(
  1933. "setProject", new Class[] {Project.class});
  1934. if (method != null) {
  1935. method.invoke(obj, new Object[] {this});
  1936. }
  1937. } catch (Throwable e) {
  1938. // ignore this if the object does not have
  1939. // a set project method or the method
  1940. // is private/protected.
  1941. }
  1942. }
  1943. }