You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

Project.java 88 kB

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