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

AjcTask.java 63KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131
  1. /* *******************************************************************
  2. * Copyright (c) 2001-2001 Xerox Corporation,
  3. * 2002 Palo Alto Research Center, Incorporated (PARC)
  4. * 2003-2004 Contributors.
  5. * All rights reserved.
  6. * This program and the accompanying materials are made available
  7. * under the terms of the Eclipse Public License v1.0
  8. * which accompanies this distribution and is available at
  9. * http://www.eclipse.org/legal/epl-v10.html
  10. *
  11. * Contributors:
  12. * Xerox/PARC initial implementation
  13. * Wes Isberg 2003-2004 changes
  14. * ******************************************************************/
  15. package org.aspectj.tools.ant.taskdefs;
  16. import java.io.File;
  17. import java.io.FileWriter;
  18. import java.io.IOException;
  19. import java.io.PrintWriter;
  20. import java.util.ArrayList;
  21. import java.util.Arrays;
  22. import java.util.Collections;
  23. import java.util.Iterator;
  24. import java.util.List;
  25. import java.util.StringTokenizer;
  26. import org.apache.tools.ant.AntClassLoader;
  27. import org.apache.tools.ant.BuildException;
  28. import org.apache.tools.ant.Location;
  29. import org.apache.tools.ant.Project;
  30. import org.apache.tools.ant.taskdefs.Copy;
  31. import org.apache.tools.ant.taskdefs.Delete;
  32. import org.apache.tools.ant.taskdefs.Execute;
  33. import org.apache.tools.ant.taskdefs.Expand;
  34. import org.apache.tools.ant.taskdefs.Javac;
  35. import org.apache.tools.ant.taskdefs.LogStreamHandler;
  36. import org.apache.tools.ant.taskdefs.MatchingTask;
  37. import org.apache.tools.ant.taskdefs.Mkdir;
  38. import org.apache.tools.ant.taskdefs.PumpStreamHandler;
  39. import org.apache.tools.ant.taskdefs.Zip;
  40. import org.apache.tools.ant.taskdefs.compilers.DefaultCompilerAdapter;
  41. import org.apache.tools.ant.types.Commandline;
  42. import org.apache.tools.ant.types.CommandlineJava;
  43. import org.apache.tools.ant.types.FileSet;
  44. import org.apache.tools.ant.types.Path;
  45. import org.apache.tools.ant.types.PatternSet;
  46. import org.apache.tools.ant.types.Reference;
  47. import org.apache.tools.ant.types.ZipFileSet;
  48. import org.apache.tools.ant.util.TaskLogger;
  49. import org.aspectj.bridge.AbortException;
  50. import org.aspectj.bridge.IMessage;
  51. import org.aspectj.bridge.IMessage.Kind;
  52. import org.aspectj.bridge.IMessageHandler;
  53. import org.aspectj.bridge.IMessageHolder;
  54. import org.aspectj.bridge.MessageHandler;
  55. import org.aspectj.bridge.MessageUtil;
  56. import org.aspectj.tools.ajc.Main;
  57. import org.aspectj.util.FileUtil;
  58. import org.aspectj.util.LangUtil;
  59. /**
  60. * This runs the AspectJ 1.1 compiler, supporting all the command-line options. In 1.1.1, ajc copies resources from input jars, but
  61. * you can copy resources from the source directories using sourceRootCopyFilter. When not forking, things will be copied as needed
  62. * for each iterative compile, but when forking things are only copied at the completion of a successful compile.
  63. * <p>
  64. * See the development environment guide for usage documentation.
  65. *
  66. * @since AspectJ 1.1, Ant 1.5
  67. */
  68. public class AjcTask extends MatchingTask {
  69. /*
  70. * This task mainly converts ant specification for ajc, verbosely ignoring improper input. It also has some special features for
  71. * non-obvious clients: (1) Javac compiler adapter supported in <code>setupAjc(AjcTask, Javac, File)</code> and
  72. * <code>readArguments(String[])</code>; (2) testing is supported by (a) permitting the same specification to be re-run with
  73. * added flags (settings once made cannot be removed); and (b) permitting recycling the task with <code>reset()</code>
  74. * (untested).
  75. *
  76. * The parts that do more than convert ant specs are (a) code for forking; (b) code for copying resources.
  77. *
  78. * If you maintain/upgrade this task, keep in mind: (1) changes to the semantics of ajc (new options, new values permitted,
  79. * etc.) will have to be reflected here. (2) the clients: the iajc ant script, Javac compiler adapter, maven clients of iajc,
  80. * and testing code.
  81. */
  82. // XXX move static methods after static initializer
  83. /**
  84. * This method extracts javac arguments to ajc, and add arguments to make ajc behave more like javac in copying resources.
  85. * <p>
  86. * Pass ajc-specific options using compilerarg sub-element:
  87. *
  88. * <pre>
  89. * &lt;javac srcdir=&quot;src&quot;&gt;
  90. * &lt;compilerarg compiler=&quot;...&quot; line=&quot;-argfile src/args.lst&quot;/&gt;
  91. * &lt;javac&gt;
  92. * </pre>
  93. *
  94. * Some javac arguments are not supported in this component (yet):
  95. *
  96. * <pre>
  97. * String memoryInitialSize;
  98. * boolean includeAntRuntime = true;
  99. * boolean includeJavaRuntime = false;
  100. * </pre>
  101. *
  102. * Other javac arguments are not supported in ajc 1.1:
  103. *
  104. * <pre>
  105. * boolean optimize;
  106. * String forkedExecutable;
  107. * FacadeTaskHelper facade;
  108. * boolean depend;
  109. * String debugLevel;
  110. * Path compileSourcepath;
  111. * </pre>
  112. *
  113. * @param javac the Javac command to implement (not null)
  114. * @param ajc the AjcTask to adapt (not null)
  115. * @param destDir the File class destination directory (may be null)
  116. * @return null if no error, or String error otherwise
  117. */
  118. public String setupAjc(Javac javac) {
  119. if (null == javac) {
  120. return "null javac";
  121. }
  122. AjcTask ajc = this;
  123. // no null checks b/c AjcTask handles null input gracefully
  124. ajc.setProject(javac.getProject());
  125. ajc.setLocation(javac.getLocation());
  126. ajc.setTaskName("javac-iajc");
  127. ajc.setDebug(javac.getDebug());
  128. ajc.setDeprecation(javac.getDeprecation());
  129. ajc.setFailonerror(javac.getFailonerror());
  130. final boolean fork = javac.isForkedJavac();
  131. ajc.setFork(fork);
  132. if (fork) {
  133. ajc.setMaxmem(javac.getMemoryMaximumSize());
  134. }
  135. ajc.setNowarn(javac.getNowarn());
  136. ajc.setListFileArgs(javac.getListfiles());
  137. ajc.setVerbose(javac.getVerbose());
  138. ajc.setTarget(javac.getTarget());
  139. ajc.setSource(javac.getSource());
  140. ajc.setEncoding(javac.getEncoding());
  141. File javacDestDir = javac.getDestdir();
  142. if (null != javacDestDir) {
  143. ajc.setDestdir(javacDestDir);
  144. // filter requires dest dir
  145. // mimic Javac task's behavior in copying resources,
  146. ajc.setSourceRootCopyFilter("**/CVS/*,**/*.java,**/*.aj");
  147. }
  148. ajc.setBootclasspath(javac.getBootclasspath());
  149. ajc.setExtdirs(javac.getExtdirs());
  150. ajc.setClasspath(javac.getClasspath());
  151. // ignore srcDir -- all files picked up in recalculated file list
  152. // ajc.setSrcDir(javac.getSrcdir());
  153. ajc.addFiles(javac.getFileList());
  154. // arguments can override the filter, add to paths, override options
  155. ajc.readArguments(javac.getCurrentCompilerArgs());
  156. return null;
  157. }
  158. /**
  159. * Find aspectjtools.jar on the task or system classpath. Accept <code>aspectj{-}tools{...}.jar</code> mainly to support build
  160. * systems using maven-style re-naming (e.g., <code>aspectj-tools-1.1.0.jar</code>. Note that we search the task classpath
  161. * first, though an entry on the system classpath would be loaded first, because it seems more correct as the more specific one.
  162. *
  163. * @return readable File for aspectjtools.jar, or null if not found.
  164. */
  165. public static File findAspectjtoolsJar() {
  166. File result = null;
  167. ClassLoader loader = AjcTask.class.getClassLoader();
  168. if (loader instanceof AntClassLoader) {
  169. AntClassLoader taskLoader = (AntClassLoader) loader;
  170. String cp = taskLoader.getClasspath();
  171. String[] cps = LangUtil.splitClasspath(cp);
  172. for (int i = 0; (i < cps.length) && (null == result); i++) {
  173. result = isAspectjtoolsjar(cps[i]);
  174. }
  175. }
  176. if (null == result) {
  177. final Path classpath = Path.systemClasspath;
  178. final String[] paths = classpath.list();
  179. for (int i = 0; (i < paths.length) && (null == result); i++) {
  180. result = isAspectjtoolsjar(paths[i]);
  181. }
  182. }
  183. return (null == result ? null : result.getAbsoluteFile());
  184. }
  185. /** @return File if readable jar with aspectj tools name, or null */
  186. private static File isAspectjtoolsjar(String path) {
  187. if (null == path) {
  188. return null;
  189. }
  190. final String prefix = "aspectj";
  191. final String infix = "tools";
  192. final String altInfix = "-tools";
  193. final String suffix = ".jar";
  194. final int prefixLength = 7; // prefix.length();
  195. final int minLength = 16;
  196. // prefixLength + infix.length() + suffix.length();
  197. if (!path.endsWith(suffix)) {
  198. return null;
  199. }
  200. int loc = path.lastIndexOf(prefix);
  201. if ((-1 != loc) && ((loc + minLength) <= path.length())) {
  202. String rest = path.substring(loc + prefixLength);
  203. if (-1 != rest.indexOf(File.pathSeparator)) {
  204. return null;
  205. }
  206. if (rest.startsWith(infix) || rest.startsWith(altInfix)) {
  207. File result = new File(path);
  208. if (result.canRead() && result.isFile()) {
  209. return result;
  210. }
  211. }
  212. }
  213. return null;
  214. }
  215. /**
  216. * Maximum length (in chars) of command line before converting to an argfile when forking
  217. */
  218. private static final int MAX_COMMANDLINE = 4096;
  219. private static final File DEFAULT_DESTDIR = new File(".") {
  220. public String toString() {
  221. return "(no destination dir specified)";
  222. }
  223. };
  224. /** do not throw BuildException on fail/abort message with usage */
  225. private static final String USAGE_SUBSTRING = "AspectJ-specific options";
  226. /** valid -X[...] options other than -Xlint variants */
  227. private static final List VALID_XOPTIONS;
  228. /** valid warning (-warn:[...]) variants */
  229. private static final List VALID_WARNINGS;
  230. /** valid debugging (-g:[...]) variants */
  231. private static final List VALID_DEBUG;
  232. /**
  233. * -Xlint variants (error, warning, ignore)
  234. *
  235. * @see org.aspectj.weaver.Lint
  236. */
  237. private static final List VALID_XLINT;
  238. public static final String COMMAND_EDITOR_NAME = AjcTask.class.getName() + ".COMMAND_EDITOR";
  239. static final String[] TARGET_INPUTS = new String[] { "1.1", "1.2", "1.3", "1.4", "1.5", "1.6", "1.7", "1.8" };
  240. static final String[] SOURCE_INPUTS = new String[] { "1.3", "1.4", "1.5", "1.6", "1.7", "1.8" };
  241. static final String[] COMPLIANCE_INPUTS = new String[] { "-1.3", "-1.4", "-1.5", "-1.6", "-1.7", "-1.8" };
  242. private static final ICommandEditor COMMAND_EDITOR;
  243. static {
  244. // many now deprecated: reweavable*
  245. String[] xs = new String[] { "serializableAspects", "incrementalFile", "lazyTjp", "reweavable", "reweavable:compress",
  246. "notReweavable", "noInline", "terminateAfterCompilation", "hasMember", "ajruntimetarget:1.2",
  247. "ajruntimetarget:1.5", "addSerialVersionUID"
  248. // , "targetNearSource", "OcodeSize",
  249. };
  250. VALID_XOPTIONS = Collections.unmodifiableList(Arrays.asList(xs));
  251. xs = new String[] { "constructorName", "packageDefaultMethod", "deprecation", "maskedCatchBlocks", "unusedLocals",
  252. "unusedArguments", "unusedImports", "syntheticAccess", "assertIdentifier", "allDeprecation", "allJavadoc",
  253. "charConcat", "conditionAssign",
  254. "emptyBlock", "fieldHiding", "finally", "indirectStatic", "intfNonInherited", "javadoc", "localHiding", "nls",
  255. "noEffectAssign", "pkgDefaultMethod", "semicolon", "unqualifiedField", "unusedPrivate", "unusedThrown",
  256. "uselessTypeCheck", "specialParamHiding", "staticReceiver", "syntheticAccess", "none" };
  257. VALID_WARNINGS = Collections.unmodifiableList(Arrays.asList(xs));
  258. xs = new String[] { "none", "lines", "vars", "source" };
  259. VALID_DEBUG = Collections.unmodifiableList(Arrays.asList(xs));
  260. xs = new String[] { "error", "warning", "ignore" };
  261. VALID_XLINT = Collections.unmodifiableList(Arrays.asList(xs));
  262. ICommandEditor editor = null;
  263. try {
  264. String editorClassName = System.getProperty(COMMAND_EDITOR_NAME);
  265. if (null != editorClassName) {
  266. ClassLoader cl = AjcTask.class.getClassLoader();
  267. Class editorClass = cl.loadClass(editorClassName);
  268. editor = (ICommandEditor) editorClass.newInstance();
  269. }
  270. } catch (Throwable t) {
  271. System.err.println("Warning: unable to load command editor");
  272. t.printStackTrace(System.err);
  273. }
  274. COMMAND_EDITOR = editor;
  275. }
  276. // ---------------------------- state and Ant interface thereto
  277. private boolean verbose;
  278. private boolean timers;
  279. private boolean listFileArgs;
  280. private boolean failonerror;
  281. private boolean fork;
  282. private String maxMem;
  283. private TaskLogger logger;
  284. // ------- single entries dumped into cmd
  285. protected GuardedCommand cmd;
  286. // ------- lists resolved in addListArgs() at execute() time
  287. private Path srcdir;
  288. private Path injars;
  289. private Path inpath;
  290. private Path classpath;
  291. private Path bootclasspath;
  292. private Path forkclasspath;
  293. private Path extdirs;
  294. private Path aspectpath;
  295. private Path argfiles;
  296. private Path inxmlfiles;
  297. private List ignored;
  298. private Path sourceRoots;
  299. private File xweaveDir;
  300. private String xdoneSignal;
  301. // ----- added by adapter - integrate better?
  302. private List /* File */adapterFiles;
  303. private String[] adapterArguments;
  304. private IMessageHolder messageHolder;
  305. private ICommandEditor commandEditor;
  306. // -------- resource-copying
  307. /** true if copying injar non-.class files to the output jar */
  308. private boolean copyInjars;
  309. private boolean copyInpath;
  310. /** non-null if copying all source root files but the filtered ones */
  311. private String sourceRootCopyFilter;
  312. /** non-null if copying all inpath dir files but the filtered ones */
  313. private String inpathDirCopyFilter;
  314. /** directory sink for classes */
  315. private File destDir;
  316. /** zip file sink for classes */
  317. private File outjar;
  318. /** track whether we've supplied any temp outjar */
  319. private boolean outjarFixedup;
  320. /**
  321. * When possibly copying resources to the output jar, pass ajc a fake output jar to copy from, so we don't change the
  322. * modification time of the output jar when copying injars/inpath into the actual outjar.
  323. */
  324. private File tmpOutjar;
  325. private boolean executing;
  326. /** non-null only while executing in same vm */
  327. private Main main;
  328. /** true only when executing in other vm */
  329. private boolean executingInOtherVM;
  330. /** true if -incremental */
  331. private boolean inIncrementalMode;
  332. /** true if -XincrementalFile (i.e, setTagFile) */
  333. private boolean inIncrementalFileMode;
  334. /** log command in non-verbose mode */
  335. private boolean logCommand;
  336. /** used when forking */
  337. private CommandlineJava javaCmd = new CommandlineJava();
  338. // also note MatchingTask grabs source files...
  339. public AjcTask() {
  340. reset();
  341. }
  342. /** to use this same Task more than once (testing) */
  343. public void reset() { // XXX possible to reset MatchingTask?
  344. // need declare for "all fields initialized in ..."
  345. adapterArguments = null;
  346. adapterFiles = new ArrayList();
  347. argfiles = null;
  348. inxmlfiles = null;
  349. executing = false;
  350. aspectpath = null;
  351. bootclasspath = null;
  352. classpath = null;
  353. cmd = new GuardedCommand();
  354. copyInjars = false;
  355. copyInpath = false;
  356. destDir = DEFAULT_DESTDIR;
  357. executing = false;
  358. executingInOtherVM = false;
  359. extdirs = null;
  360. failonerror = true; // non-standard default
  361. forkclasspath = null;
  362. inIncrementalMode = false;
  363. inIncrementalFileMode = false;
  364. ignored = new ArrayList();
  365. injars = null;
  366. inpath = null;
  367. listFileArgs = false;
  368. maxMem = null;
  369. messageHolder = null;
  370. outjar = null;
  371. sourceRootCopyFilter = null;
  372. inpathDirCopyFilter = null;
  373. sourceRoots = null;
  374. srcdir = null;
  375. tmpOutjar = null;
  376. verbose = false;
  377. timers = false;
  378. xweaveDir = null;
  379. xdoneSignal = null;
  380. logCommand = false;
  381. javaCmd = new CommandlineJava();
  382. }
  383. protected void ignore(String ignored) {
  384. this.ignored.add(ignored + " at " + getLocation());
  385. }
  386. // ---------------------- option values
  387. // used by entries with internal commas
  388. protected String validCommaList(String list, List valid, String label) {
  389. return validCommaList(list, valid, label, valid.size());
  390. }
  391. protected String validCommaList(String list, List valid, String label, int max) {
  392. StringBuffer result = new StringBuffer();
  393. StringTokenizer st = new StringTokenizer(list, ",");
  394. int num = 0;
  395. while (st.hasMoreTokens()) {
  396. String token = st.nextToken().trim();
  397. num++;
  398. if (num > max) {
  399. ignore("too many entries for -" + label + ": " + token);
  400. break;
  401. }
  402. if (!valid.contains(token)) {
  403. ignore("bad commaList entry for -" + label + ": " + token);
  404. } else {
  405. if (0 < result.length()) {
  406. result.append(",");
  407. }
  408. result.append(token);
  409. }
  410. }
  411. return (0 == result.length() ? null : result.toString());
  412. }
  413. /**
  414. * Controls whether annotation processing and/or compilation is done.
  415. * -proc:none means that compilation takes place without annotation processing.
  416. * -proc:only means that only annotation processing is done, without any subsequent compilation.
  417. */
  418. public void setProc(String proc) {
  419. if (proc.equals("none")) {
  420. cmd.addFlag("-proc:none", true);
  421. } else if (proc.equals("only")) {
  422. cmd.addFlag("-proc:only", true);
  423. }
  424. }
  425. /**
  426. * -processor class1[,class2,class3...]
  427. * Names of the annotation processors to run. This bypasses the default discovery process.
  428. */
  429. public void setProcessor(String processors) {
  430. cmd.addFlagged("-processor", processors);
  431. }
  432. /**
  433. * -processorpath path
  434. * Specify where to find annotation processors; if this option is not used, the class path will be searched for processors.
  435. */
  436. public void setProcessorpath(String processorpath) {
  437. cmd.addFlagged("-processorpath", processorpath);
  438. }
  439. /**
  440. * -s dir
  441. * Specify the directory where to place generated source files. The directory must already exist; javac will not create it.
  442. * If a class is part of a package, the compiler puts the source file in a subdirectory reflecting the package name,
  443. * creating directories as needed.
  444. *
  445. * For example, if you specify -s C:\mysrc and the class is called com.mypackage.MyClass,
  446. * then the source file will be placed in C:\mysrc\com\mypackage\MyClass.java.
  447. */
  448. public void setS(String s) {
  449. cmd.addFlagged("-s", s);
  450. }
  451. public void setIncremental(boolean incremental) {
  452. cmd.addFlag("-incremental", incremental);
  453. inIncrementalMode = incremental;
  454. }
  455. public void setLogCommand(boolean logCommand) {
  456. this.logCommand = logCommand;
  457. }
  458. public void setHelp(boolean help) {
  459. cmd.addFlag("-help", help);
  460. }
  461. public void setVersion(boolean version) {
  462. cmd.addFlag("-version", version);
  463. }
  464. public void setXTerminateAfterCompilation(boolean b) {
  465. cmd.addFlag("-XterminateAfterCompilation", b);
  466. }
  467. public void setXReweavable(boolean reweavable) {
  468. cmd.addFlag("-Xreweavable", reweavable);
  469. }
  470. public void setXmlConfigured(boolean xmlConfigured) {
  471. cmd.addFlag("-xmlConfigured", xmlConfigured);
  472. }
  473. public void setXJoinpoints(String optionalJoinpoints) {
  474. cmd.addFlag("-Xjoinpoints:" + optionalJoinpoints, true);
  475. }
  476. public void setCheckRuntimeVersion(boolean b) {
  477. cmd.addFlag("-checkRuntimeVersion:" + b, true);
  478. }
  479. public void setXNoWeave(boolean b) {
  480. if (logger != null) {
  481. logger.warning("the noweave option is no longer required and is being ignored");
  482. }
  483. }
  484. public void setNoWeave(boolean b) {
  485. if (logger != null) {
  486. logger.warning("the noweave option is no longer required and is being ignored");
  487. }
  488. }
  489. public void setXNotReweavable(boolean notReweavable) {
  490. cmd.addFlag("-XnotReweavable", notReweavable);
  491. }
  492. public void setXaddSerialVersionUID(boolean addUID) {
  493. cmd.addFlag("-XaddSerialVersionUID", addUID);
  494. }
  495. public void setXNoInline(boolean noInline) {
  496. cmd.addFlag("-XnoInline", noInline);
  497. }
  498. public void setShowWeaveInfo(boolean showweaveinfo) {
  499. cmd.addFlag("-showWeaveInfo", showweaveinfo);
  500. }
  501. public void setNowarn(boolean nowarn) {
  502. cmd.addFlag("-nowarn", nowarn);
  503. }
  504. public void setDeprecation(boolean deprecation) {
  505. cmd.addFlag("-deprecation", deprecation);
  506. }
  507. public void setWarn(String warnings) {
  508. warnings = validCommaList(warnings, VALID_WARNINGS, "warn");
  509. cmd.addFlag("-warn:" + warnings, (null != warnings));
  510. }
  511. public void setDebug(boolean debug) {
  512. cmd.addFlag("-g", debug);
  513. }
  514. public void setDebugLevel(String level) {
  515. level = validCommaList(level, VALID_DEBUG, "g");
  516. cmd.addFlag("-g:" + level, (null != level));
  517. }
  518. public void setEmacssym(boolean emacssym) {
  519. cmd.addFlag("-emacssym", emacssym);
  520. }
  521. public void setCrossrefs(boolean on) {
  522. cmd.addFlag("-crossrefs", on);
  523. }
  524. /**
  525. * -Xlint - set default level of -Xlint messages to warning (same as </code>-Xlint:warning</code>)
  526. */
  527. public void setXlintwarnings(boolean xlintwarnings) {
  528. cmd.addFlag("-Xlint", xlintwarnings);
  529. }
  530. /**
  531. * -Xlint:{error|warning|info} - set default level for -Xlint messages
  532. *
  533. * @param xlint the String with one of error, warning, ignored
  534. */
  535. public void setXlint(String xlint) {
  536. xlint = validCommaList(xlint, VALID_XLINT, "Xlint", 1);
  537. cmd.addFlag("-Xlint:" + xlint, (null != xlint));
  538. }
  539. /**
  540. * -Xlintfile {lint.properties} - enable or disable specific forms of -Xlint messages based on a lint properties file (default
  541. * is <code>org/aspectj/weaver/XLintDefault.properties</code>)
  542. *
  543. * @param xlintFile the File with lint properties
  544. */
  545. public void setXlintfile(File xlintFile) {
  546. cmd.addFlagged("-Xlintfile", xlintFile.getAbsolutePath());
  547. }
  548. public void setPreserveAllLocals(boolean preserveAllLocals) {
  549. cmd.addFlag("-preserveAllLocals", preserveAllLocals);
  550. }
  551. public void setNoImportError(boolean noImportError) {
  552. cmd.addFlag("-warn:-unusedImport", noImportError);
  553. }
  554. public void setEncoding(String encoding) {
  555. cmd.addFlagged("-encoding", encoding);
  556. }
  557. public void setLog(File file) {
  558. cmd.addFlagged("-log", file.getAbsolutePath());
  559. }
  560. public void setProceedOnError(boolean proceedOnError) {
  561. cmd.addFlag("-proceedOnError", proceedOnError);
  562. }
  563. public void setVerbose(boolean verbose) {
  564. cmd.addFlag("-verbose", verbose);
  565. this.verbose = verbose;
  566. }
  567. public void setTimers(boolean timers) {
  568. cmd.addFlag("-timers", timers);
  569. this.timers = timers;
  570. }
  571. public void setListFileArgs(boolean listFileArgs) {
  572. this.listFileArgs = listFileArgs;
  573. }
  574. public void setReferenceInfo(boolean referenceInfo) {
  575. cmd.addFlag("-referenceInfo", referenceInfo);
  576. }
  577. public void setTime(boolean time) {
  578. cmd.addFlag("-time", time);
  579. }
  580. public void setNoExit(boolean noExit) {
  581. cmd.addFlag("-noExit", noExit);
  582. }
  583. public void setFailonerror(boolean failonerror) {
  584. this.failonerror = failonerror;
  585. }
  586. /**
  587. * @return true if fork was set
  588. */
  589. public boolean isForked() {
  590. return fork;
  591. }
  592. public void setFork(boolean fork) {
  593. this.fork = fork;
  594. }
  595. public void setMaxmem(String maxMem) {
  596. this.maxMem = maxMem;
  597. }
  598. /** support for nested &lt;jvmarg&gt; elements */
  599. public Commandline.Argument createJvmarg() {
  600. return this.javaCmd.createVmArgument();
  601. }
  602. // ----------------
  603. public void setTagFile(File file) {
  604. inIncrementalMode = true;
  605. cmd.addFlagged(Main.CommandController.TAG_FILE_OPTION, file.getAbsolutePath());
  606. inIncrementalFileMode = true;
  607. }
  608. public void setOutjar(File file) {
  609. if (DEFAULT_DESTDIR != destDir) {
  610. String e = "specifying both output jar (" + file + ") and destination dir (" + destDir + ")";
  611. throw new BuildException(e);
  612. }
  613. outjar = file;
  614. outjarFixedup = false;
  615. tmpOutjar = null;
  616. }
  617. public void setOutxml(boolean outxml) {
  618. cmd.addFlag("-outxml", outxml);
  619. }
  620. public void setOutxmlfile(String name) {
  621. cmd.addFlagged("-outxmlfile", name);
  622. }
  623. public void setDestdir(File dir) {
  624. if (null != outjar) {
  625. String e = "specifying both output jar (" + outjar + ") and destination dir (" + dir + ")";
  626. throw new BuildException(e);
  627. }
  628. cmd.addFlagged("-d", dir.getAbsolutePath());
  629. destDir = dir;
  630. }
  631. /**
  632. * @param input a String in TARGET_INPUTS
  633. */
  634. public void setTarget(String input) {
  635. String ignore = cmd.addOption("-target", TARGET_INPUTS, input);
  636. if (null != ignore) {
  637. ignore(ignore);
  638. }
  639. }
  640. /**
  641. * Language compliance level. If not set explicitly, eclipse default holds.
  642. *
  643. * @param input a String in COMPLIANCE_INPUTS
  644. */
  645. public void setCompliance(String input) {
  646. String ignore = cmd.addOption(null, COMPLIANCE_INPUTS, input);
  647. if (null != ignore) {
  648. ignore(ignore);
  649. }
  650. }
  651. /**
  652. * Source compliance level. If not set explicitly, eclipse default holds.
  653. *
  654. * @param input a String in SOURCE_INPUTS
  655. */
  656. public void setSource(String input) {
  657. String ignore = cmd.addOption("-source", SOURCE_INPUTS, input);
  658. if (null != ignore) {
  659. ignore(ignore);
  660. }
  661. }
  662. public void setParameters(boolean b) {
  663. cmd.addFlag("-parameters",b);
  664. }
  665. /**
  666. * Flag to copy all non-.class contents of injars to outjar after compile completes. Requires both injars and outjar.
  667. *
  668. * @param doCopy
  669. */
  670. public void setCopyInjars(boolean doCopy) {
  671. ignore("copyInJars");
  672. log("copyInjars not required since 1.1.1.\n", Project.MSG_WARN);
  673. // this.copyInjars = doCopy;
  674. }
  675. /**
  676. * Option to copy all files from all source root directories except those specified here. If this is specified and sourceroots
  677. * are specified, then this will copy all files except those specified in the filter pattern. Requires sourceroots.
  678. *
  679. * @param filter a String acceptable as an excludes filter for an Ant Zip fileset.
  680. */
  681. public void setSourceRootCopyFilter(String filter) {
  682. this.sourceRootCopyFilter = filter;
  683. }
  684. /**
  685. * Option to copy all files from all inpath directories except the files specified here. If this is specified and inpath
  686. * directories are specified, then this will copy all files except those specified in the filter pattern. Requires inpath. If
  687. * the input does not contain "**\/*.class", then this prepends it, to avoid overwriting woven classes with unwoven input.
  688. *
  689. * @param filter a String acceptable as an excludes filter for an Ant Zip fileset.
  690. */
  691. public void setInpathDirCopyFilter(String filter) {
  692. if (null != filter) {
  693. if (-1 == filter.indexOf("**/*.class")) {
  694. filter = "**/*.class," + filter;
  695. }
  696. }
  697. this.inpathDirCopyFilter = filter;
  698. }
  699. public void setX(String input) { // ajc-only eajc-also docDone
  700. StringTokenizer tokens = new StringTokenizer(input, ",", false);
  701. while (tokens.hasMoreTokens()) {
  702. String token = tokens.nextToken().trim();
  703. if (1 < token.length()) {
  704. // new special case: allow -Xset:anything
  705. if (VALID_XOPTIONS.contains(token) || token.indexOf("set:") == 0 || token.indexOf("joinpoints:") == 0) {
  706. cmd.addFlag("-X" + token, true);
  707. } else {
  708. ignore("-X" + token);
  709. }
  710. }
  711. }
  712. }
  713. public void setXDoneSignal(String doneSignal) {
  714. this.xdoneSignal = doneSignal;
  715. }
  716. /** direct API for testing */
  717. public void setMessageHolder(IMessageHolder holder) {
  718. this.messageHolder = holder;
  719. }
  720. /**
  721. * Setup custom message handling.
  722. *
  723. * @param className the String fully-qualified-name of a class reachable from this object's class loader, implementing
  724. * IMessageHolder, and having a public no-argument constructor.
  725. * @throws BuildException if unable to create instance of className
  726. */
  727. public void setMessageHolderClass(String className) {
  728. try {
  729. Class mclass = Class.forName(className);
  730. IMessageHolder holder = (IMessageHolder) mclass.newInstance();
  731. setMessageHolder(holder);
  732. } catch (Throwable t) {
  733. String m = "unable to instantiate message holder: " + className;
  734. throw new BuildException(m, t);
  735. }
  736. }
  737. /** direct API for testing */
  738. public void setCommandEditor(ICommandEditor editor) {
  739. this.commandEditor = editor;
  740. }
  741. /**
  742. * Setup command-line filter. To do this staticly, define the environment variable
  743. * <code>org.aspectj.tools.ant.taskdefs.AjcTask.COMMAND_EDITOR</code> with the <code>className</code> parameter.
  744. *
  745. * @param className the String fully-qualified-name of a class reachable from this object's class loader, implementing
  746. * ICommandEditor, and having a public no-argument constructor.
  747. * @throws BuildException if unable to create instance of className
  748. */
  749. public void setCommandEditorClass(String className) { // skip Ant interface?
  750. try {
  751. Class mclass = Class.forName(className);
  752. setCommandEditor((ICommandEditor) mclass.newInstance());
  753. } catch (Throwable t) {
  754. String m = "unable to instantiate command editor: " + className;
  755. throw new BuildException(m, t);
  756. }
  757. }
  758. // ---------------------- Path lists
  759. /**
  760. * Add path elements to source path and return result. Elements are added even if they do not exist.
  761. *
  762. * @param source the Path to add to - may be null
  763. * @param toAdd the Path to add - may be null
  764. * @return the (never-null) Path that results
  765. */
  766. protected Path incPath(Path source, Path toAdd) {
  767. if (null == source) {
  768. source = new Path(project);
  769. }
  770. if (null != toAdd) {
  771. source.append(toAdd);
  772. }
  773. return source;
  774. }
  775. public void setSourcerootsref(Reference ref) {
  776. createSourceRoots().setRefid(ref);
  777. }
  778. public void setSourceRoots(Path roots) {
  779. sourceRoots = incPath(sourceRoots, roots);
  780. }
  781. public Path createSourceRoots() {
  782. if (sourceRoots == null) {
  783. sourceRoots = new Path(project);
  784. }
  785. return sourceRoots.createPath();
  786. }
  787. public void setXWeaveDir(File file) {
  788. if ((null != file) && file.isDirectory() && file.canRead()) {
  789. xweaveDir = file;
  790. }
  791. }
  792. public void setInjarsref(Reference ref) {
  793. createInjars().setRefid(ref);
  794. }
  795. public void setInpathref(Reference ref) {
  796. createInpath().setRefid(ref);
  797. }
  798. public void setInjars(Path path) {
  799. injars = incPath(injars, path);
  800. }
  801. public void setInpath(Path path) {
  802. inpath = incPath(inpath, path);
  803. }
  804. public Path createInjars() {
  805. if (injars == null) {
  806. injars = new Path(project);
  807. }
  808. return injars.createPath();
  809. }
  810. public Path createInpath() {
  811. if (inpath == null) {
  812. inpath = new Path(project);
  813. }
  814. return inpath.createPath();
  815. }
  816. public void setClasspath(Path path) {
  817. classpath = incPath(classpath, path);
  818. }
  819. public void setClasspathref(Reference classpathref) {
  820. createClasspath().setRefid(classpathref);
  821. }
  822. public Path createClasspath() {
  823. if (classpath == null) {
  824. classpath = new Path(project);
  825. }
  826. return classpath.createPath();
  827. }
  828. public void setBootclasspath(Path path) {
  829. bootclasspath = incPath(bootclasspath, path);
  830. }
  831. public void setBootclasspathref(Reference bootclasspathref) {
  832. createBootclasspath().setRefid(bootclasspathref);
  833. }
  834. public Path createBootclasspath() {
  835. if (bootclasspath == null) {
  836. bootclasspath = new Path(project);
  837. }
  838. return bootclasspath.createPath();
  839. }
  840. public void setForkclasspath(Path path) {
  841. forkclasspath = incPath(forkclasspath, path);
  842. }
  843. public void setForkclasspathref(Reference forkclasspathref) {
  844. createForkclasspath().setRefid(forkclasspathref);
  845. }
  846. public Path createForkclasspath() {
  847. if (forkclasspath == null) {
  848. forkclasspath = new Path(project);
  849. }
  850. return forkclasspath.createPath();
  851. }
  852. public void setExtdirs(Path path) {
  853. extdirs = incPath(extdirs, path);
  854. }
  855. public void setExtdirsref(Reference ref) {
  856. createExtdirs().setRefid(ref);
  857. }
  858. public Path createExtdirs() {
  859. if (extdirs == null) {
  860. extdirs = new Path(project);
  861. }
  862. return extdirs.createPath();
  863. }
  864. public void setAspectpathref(Reference ref) {
  865. createAspectpath().setRefid(ref);
  866. }
  867. public void setAspectpath(Path path) {
  868. aspectpath = incPath(aspectpath, path);
  869. }
  870. public Path createAspectpath() {
  871. if (aspectpath == null) {
  872. aspectpath = new Path(project);
  873. }
  874. return aspectpath.createPath();
  875. }
  876. public void setSrcDir(Path path) {
  877. srcdir = incPath(srcdir, path);
  878. }
  879. public Path createSrc() {
  880. return createSrcdir();
  881. }
  882. public Path createSrcdir() {
  883. if (srcdir == null) {
  884. srcdir = new Path(project);
  885. }
  886. return srcdir.createPath();
  887. }
  888. /** @return true if in incremental mode (command-line or file) */
  889. public boolean isInIncrementalMode() {
  890. return inIncrementalMode;
  891. }
  892. /** @return true if in incremental file mode */
  893. public boolean isInIncrementalFileMode() {
  894. return inIncrementalFileMode;
  895. }
  896. public void setArgfilesref(Reference ref) {
  897. createArgfiles().setRefid(ref);
  898. }
  899. public void setArgfiles(Path path) { // ajc-only eajc-also docDone
  900. argfiles = incPath(argfiles, path);
  901. }
  902. public Path createArgfiles() {
  903. if (argfiles == null) {
  904. argfiles = new Path(project);
  905. }
  906. return argfiles.createPath();
  907. }
  908. public void setInxmlref(Reference ref) {
  909. createArgfiles().setRefid(ref);
  910. }
  911. public void setInxml(Path path) { // ajc-only eajc-also docDone
  912. inxmlfiles = incPath(inxmlfiles, path);
  913. }
  914. public Path createInxml() {
  915. if (inxmlfiles == null) {
  916. inxmlfiles = new Path(project);
  917. }
  918. return inxmlfiles.createPath();
  919. }
  920. // ------------------------------ run
  921. /**
  922. * Compile using ajc per settings.
  923. *
  924. * @exception BuildException if the compilation has problems or if there were compiler errors and failonerror is true.
  925. */
  926. public void execute() throws BuildException {
  927. this.logger = new TaskLogger(this);
  928. if (executing) {
  929. throw new IllegalStateException("already executing");
  930. } else {
  931. executing = true;
  932. }
  933. setupOptions();
  934. verifyOptions();
  935. try {
  936. String[] args = makeCommand();
  937. if (logCommand) {
  938. log("ajc " + Arrays.asList(args));
  939. } else {
  940. logVerbose("ajc " + Arrays.asList(args));
  941. }
  942. if (!fork) {
  943. executeInSameVM(args);
  944. } else { // when forking, Adapter handles failonerror
  945. executeInOtherVM(args);
  946. }
  947. } catch (BuildException e) {
  948. throw e;
  949. } catch (Throwable x) {
  950. this.logger.error(Main.renderExceptionForUser(x));
  951. throw new BuildException("IGNORE -- See " + LangUtil.unqualifiedClassName(x) + " rendered to ant logger");
  952. } finally {
  953. executing = false;
  954. if (null != tmpOutjar) {
  955. tmpOutjar.delete();
  956. }
  957. }
  958. }
  959. /**
  960. * Halt processing. This tells main in the same vm to quit. It fails when running in forked mode.
  961. *
  962. * @return true if not in forked mode and main has quit or been told to quit
  963. */
  964. public boolean quit() {
  965. if (executingInOtherVM) {
  966. return false;
  967. }
  968. Main me = main;
  969. if (null != me) {
  970. me.quit();
  971. }
  972. return true;
  973. }
  974. // package-private for testing
  975. String[] makeCommand() {
  976. ArrayList result = new ArrayList();
  977. if (0 < ignored.size()) {
  978. for (Iterator iter = ignored.iterator(); iter.hasNext();) {
  979. logVerbose("ignored: " + iter.next());
  980. }
  981. }
  982. // when copying resources, use temp jar for class output
  983. // then copy temp jar contents and resources to output jar
  984. if ((null != outjar) && !outjarFixedup) {
  985. if (copyInjars || copyInpath || (null != sourceRootCopyFilter) || (null != inpathDirCopyFilter)) {
  986. String path = outjar.getAbsolutePath();
  987. int len = FileUtil.zipSuffixLength(path);
  988. path = path.substring(0, path.length() - len) + ".tmp.jar";
  989. tmpOutjar = new File(path);
  990. }
  991. if (null == tmpOutjar) {
  992. cmd.addFlagged("-outjar", outjar.getAbsolutePath());
  993. } else {
  994. cmd.addFlagged("-outjar", tmpOutjar.getAbsolutePath());
  995. }
  996. outjarFixedup = true;
  997. }
  998. result.addAll(cmd.extractArguments());
  999. addListArgs(result);
  1000. String[] command = (String[]) result.toArray(new String[0]);
  1001. if (null != commandEditor) {
  1002. command = commandEditor.editCommand(command);
  1003. } else if (null != COMMAND_EDITOR) {
  1004. command = COMMAND_EDITOR.editCommand(command);
  1005. }
  1006. return command;
  1007. }
  1008. /**
  1009. * Create any pseudo-options required to implement some of the macro options
  1010. *
  1011. * @throws BuildException if options conflict
  1012. */
  1013. protected void setupOptions() {
  1014. if (null != xweaveDir) {
  1015. if (DEFAULT_DESTDIR != destDir) {
  1016. throw new BuildException("weaveDir forces destdir");
  1017. }
  1018. if (null != outjar) {
  1019. throw new BuildException("weaveDir forces outjar");
  1020. }
  1021. if (null != injars) {
  1022. throw new BuildException("weaveDir incompatible with injars now");
  1023. }
  1024. if (null != inpath) {
  1025. throw new BuildException("weaveDir incompatible with inpath now");
  1026. }
  1027. File injar = zipDirectory(xweaveDir);
  1028. setInjars(new Path(getProject(), injar.getAbsolutePath()));
  1029. setDestdir(xweaveDir);
  1030. }
  1031. }
  1032. protected File zipDirectory(File dir) {
  1033. File tempDir = new File(".");
  1034. try {
  1035. tempDir = File.createTempFile("AjcTest", ".tmp");
  1036. tempDir.mkdirs();
  1037. tempDir.deleteOnExit(); // XXX remove zip explicitly..
  1038. } catch (IOException e) {
  1039. // ignore
  1040. }
  1041. // File result = new File(tempDir,
  1042. String filename = "AjcTask-" + System.currentTimeMillis() + ".zip";
  1043. File result = new File(filename);
  1044. Zip zip = new Zip();
  1045. zip.setProject(getProject());
  1046. zip.setDestFile(result);
  1047. zip.setTaskName(getTaskName() + " - zip");
  1048. FileSet fileset = new FileSet();
  1049. fileset.setDir(dir);
  1050. zip.addFileset(fileset);
  1051. zip.execute();
  1052. Delete delete = new Delete();
  1053. delete.setProject(getProject());
  1054. delete.setTaskName(getTaskName() + " - delete");
  1055. delete.setDir(dir);
  1056. delete.execute();
  1057. Mkdir mkdir = new Mkdir();
  1058. mkdir.setProject(getProject());
  1059. mkdir.setTaskName(getTaskName() + " - mkdir");
  1060. mkdir.setDir(dir);
  1061. mkdir.execute();
  1062. return result;
  1063. }
  1064. /**
  1065. * @throw BuildException if options conflict
  1066. */
  1067. protected void verifyOptions() {
  1068. StringBuffer sb = new StringBuffer();
  1069. if (fork && isInIncrementalMode() && !isInIncrementalFileMode()) {
  1070. sb.append("can fork incremental only using tag file.\n");
  1071. }
  1072. if (((null != inpathDirCopyFilter) || (null != sourceRootCopyFilter)) && (null == outjar) && (DEFAULT_DESTDIR == destDir)) {
  1073. final String REQ = " requires dest dir or output jar.\n";
  1074. if (null == inpathDirCopyFilter) {
  1075. sb.append("sourceRootCopyFilter");
  1076. } else if (null == sourceRootCopyFilter) {
  1077. sb.append("inpathDirCopyFilter");
  1078. } else {
  1079. sb.append("sourceRootCopyFilter and inpathDirCopyFilter");
  1080. }
  1081. sb.append(REQ);
  1082. }
  1083. if (0 < sb.length()) {
  1084. throw new BuildException(sb.toString());
  1085. }
  1086. }
  1087. /**
  1088. * Run the compile in the same VM by loading the compiler (Main), setting up any message holders, doing the compile, and
  1089. * converting abort/failure and error messages to BuildException, as appropriate.
  1090. *
  1091. * @throws BuildException if abort or failure messages or if errors and failonerror.
  1092. *
  1093. */
  1094. protected void executeInSameVM(String[] args) {
  1095. if (null != maxMem) {
  1096. log("maxMem ignored unless forked: " + maxMem, Project.MSG_WARN);
  1097. }
  1098. IMessageHolder holder = messageHolder;
  1099. int numPreviousErrors;
  1100. if (null == holder) {
  1101. MessageHandler mhandler = new MessageHandler(true);
  1102. final IMessageHandler delegate;
  1103. delegate = new AntMessageHandler(this.logger, this.verbose, false);
  1104. mhandler.setInterceptor(delegate);
  1105. holder = mhandler;
  1106. numPreviousErrors = 0;
  1107. } else {
  1108. numPreviousErrors = holder.numMessages(IMessage.ERROR, true);
  1109. }
  1110. {
  1111. Main newmain = new Main();
  1112. newmain.setHolder(holder);
  1113. newmain.setCompletionRunner(new Runnable() {
  1114. public void run() {
  1115. doCompletionTasks();
  1116. }
  1117. });
  1118. if (null != main) {
  1119. MessageUtil.fail(holder, "still running prior main");
  1120. return;
  1121. }
  1122. main = newmain;
  1123. }
  1124. main.runMain(args, false);
  1125. if (failonerror) {
  1126. int errs = holder.numMessages(IMessage.ERROR, false);
  1127. errs -= numPreviousErrors;
  1128. if (0 < errs) {
  1129. String m = errs + " errors";
  1130. MessageUtil.print(System.err, holder, "", MessageUtil.MESSAGE_ALL, MessageUtil.PICK_ERROR, true);
  1131. throw new BuildException(m);
  1132. }
  1133. }
  1134. // Throw BuildException if there are any fail or abort
  1135. // messages.
  1136. // The BuildException message text has a list of class names
  1137. // for the exceptions found in the messages, or the
  1138. // number of fail/abort messages found if there were
  1139. // no exceptions for any of the fail/abort messages.
  1140. // The interceptor message handler should have already
  1141. // printed the messages, including any stack traces.
  1142. // HACK: this ignores the Usage message
  1143. {
  1144. IMessage[] fails = holder.getMessages(IMessage.FAIL, true);
  1145. if (!LangUtil.isEmpty(fails)) {
  1146. StringBuffer sb = new StringBuffer();
  1147. String prefix = "fail due to ";
  1148. int numThrown = 0;
  1149. for (int i = 0; i < fails.length; i++) {
  1150. String message = fails[i].getMessage();
  1151. if (LangUtil.isEmpty(message)) {
  1152. message = "<no message>";
  1153. } else if (-1 != message.indexOf(USAGE_SUBSTRING)) {
  1154. continue;
  1155. }
  1156. Throwable t = fails[i].getThrown();
  1157. if (null != t) {
  1158. numThrown++;
  1159. sb.append(prefix);
  1160. sb.append(LangUtil.unqualifiedClassName(t.getClass()));
  1161. String thrownMessage = t.getMessage();
  1162. if (!LangUtil.isEmpty(thrownMessage)) {
  1163. sb.append(" \"" + thrownMessage + "\"");
  1164. }
  1165. }
  1166. sb.append("\"" + message + "\"");
  1167. prefix = ", ";
  1168. }
  1169. if (0 < sb.length()) {
  1170. sb.append(" (" + numThrown + " exceptions)");
  1171. throw new BuildException(sb.toString());
  1172. }
  1173. }
  1174. }
  1175. }
  1176. /**
  1177. * Execute in a separate VM. Differences from normal same-VM execution:
  1178. * <ul>
  1179. * <li>ignores any message holder {class} set</li>
  1180. * <li>No resource-copying between interative runs</li>
  1181. * <li>failonerror fails when process interface fails to return negative values</li>
  1182. * </ul>
  1183. *
  1184. * @param args String[] of the complete compiler command to execute
  1185. *
  1186. * @see DefaultCompilerAdapter#executeExternalCompile(String[], int)
  1187. * @throws BuildException if ajc aborts (negative value) or if failonerror and there were compile errors.
  1188. */
  1189. protected void executeInOtherVM(String[] args) {
  1190. javaCmd.setClassname(org.aspectj.tools.ajc.Main.class.getName());
  1191. final Path vmClasspath = javaCmd.createClasspath(getProject());
  1192. {
  1193. File aspectjtools = null;
  1194. int vmClasspathSize = vmClasspath.size();
  1195. if ((null != forkclasspath) && (0 != forkclasspath.size())) {
  1196. vmClasspath.addExisting(forkclasspath);
  1197. } else {
  1198. aspectjtools = findAspectjtoolsJar();
  1199. if (null != aspectjtools) {
  1200. vmClasspath.createPathElement().setLocation(aspectjtools);
  1201. }
  1202. }
  1203. int newVmClasspathSize = vmClasspath.size();
  1204. if (vmClasspathSize == newVmClasspathSize) {
  1205. String m = "unable to find aspectjtools to fork - ";
  1206. if (null != aspectjtools) {
  1207. m += "tried " + aspectjtools.toString();
  1208. } else if (null != forkclasspath) {
  1209. m += "tried " + forkclasspath.toString();
  1210. } else {
  1211. m += "define forkclasspath or put aspectjtools on classpath";
  1212. }
  1213. throw new BuildException(m);
  1214. }
  1215. }
  1216. if (null != maxMem) {
  1217. javaCmd.setMaxmemory(maxMem);
  1218. }
  1219. File tempFile = null;
  1220. int numArgs = args.length;
  1221. args = GuardedCommand.limitTo(args, MAX_COMMANDLINE, getLocation());
  1222. if (args.length != numArgs) {
  1223. tempFile = new File(args[1]);
  1224. }
  1225. try {
  1226. boolean setMessageHolderOnForking = (this.messageHolder != null);
  1227. String[] javaArgs = javaCmd.getCommandline();
  1228. String[] both = new String[javaArgs.length + args.length + (setMessageHolderOnForking ? 2 : 0)];
  1229. System.arraycopy(javaArgs, 0, both, 0, javaArgs.length);
  1230. System.arraycopy(args, 0, both, javaArgs.length, args.length);
  1231. if (setMessageHolderOnForking) {
  1232. both[both.length - 2] = "-messageHolder";
  1233. both[both.length - 1] = this.messageHolder.getClass().getName();
  1234. }
  1235. // try to use javaw instead on windows
  1236. if (both[0].endsWith("java.exe")) {
  1237. String path = both[0];
  1238. path = path.substring(0, path.length() - 4);
  1239. path = path + "w.exe";
  1240. File javaw = new File(path);
  1241. if (javaw.canRead() && javaw.isFile()) {
  1242. both[0] = path;
  1243. }
  1244. }
  1245. logVerbose("forking " + Arrays.asList(both));
  1246. int result = execInOtherVM(both);
  1247. if (0 > result) {
  1248. throw new BuildException("failure[" + result + "] running ajc");
  1249. } else if (failonerror && (0 < result)) {
  1250. throw new BuildException("compile errors: " + result);
  1251. }
  1252. // when forking, do completion only at end and when successful
  1253. doCompletionTasks();
  1254. } finally {
  1255. if (null != tempFile) {
  1256. tempFile.delete();
  1257. }
  1258. }
  1259. }
  1260. /**
  1261. * Execute in another process using the same JDK and the base directory of the project. XXX correct?
  1262. *
  1263. * @param args
  1264. * @return
  1265. */
  1266. protected int execInOtherVM(String[] args) {
  1267. try {
  1268. Project project = getProject();
  1269. PumpStreamHandler handler = new LogStreamHandler(this, verbose ? Project.MSG_VERBOSE : Project.MSG_INFO,
  1270. Project.MSG_WARN);
  1271. // replace above two lines with what follows as an aid to debugging when running the unit tests....
  1272. // LogStreamHandler handler = new LogStreamHandler(this,
  1273. // Project.MSG_INFO, Project.MSG_WARN) {
  1274. //
  1275. // ByteArrayOutputStream baos = new ByteArrayOutputStream();
  1276. // /* (non-Javadoc)
  1277. // * @see org.apache.tools.ant.taskdefs.PumpStreamHandler#createProcessOutputPump(java.io.InputStream,
  1278. // java.io.OutputStream)
  1279. // */
  1280. // protected void createProcessErrorPump(InputStream is,
  1281. // OutputStream os) {
  1282. // super.createProcessErrorPump(is, baos);
  1283. // }
  1284. //
  1285. // /* (non-Javadoc)
  1286. // * @see org.apache.tools.ant.taskdefs.LogStreamHandler#stop()
  1287. // */
  1288. // public void stop() {
  1289. // byte[] written = baos.toByteArray();
  1290. // System.err.print(new String(written));
  1291. // super.stop();
  1292. // }
  1293. // };
  1294. Execute exe = new Execute(handler);
  1295. exe.setAntRun(project);
  1296. exe.setWorkingDirectory(project.getBaseDir());
  1297. exe.setCommandline(args);
  1298. try {
  1299. if (executingInOtherVM) {
  1300. String s = "already running in other vm?";
  1301. throw new BuildException(s, location);
  1302. }
  1303. executingInOtherVM = true;
  1304. exe.execute();
  1305. } finally {
  1306. executingInOtherVM = false;
  1307. }
  1308. return exe.getExitValue();
  1309. } catch (IOException e) {
  1310. String m = "Error executing command " + Arrays.asList(args);
  1311. throw new BuildException(m, e, location);
  1312. }
  1313. }
  1314. // ------------------------------ setup and reporting
  1315. /** @return null if path null or empty, String rendition otherwise */
  1316. protected static void addFlaggedPath(String flag, Path path, List list) {
  1317. if (!LangUtil.isEmpty(flag) && ((null != path) && (0 < path.size()))) {
  1318. list.add(flag);
  1319. list.add(path.toString());
  1320. }
  1321. }
  1322. /**
  1323. * Add to list any path or plural arguments.
  1324. */
  1325. protected void addListArgs(List list) throws BuildException {
  1326. addFlaggedPath("-classpath", classpath, list);
  1327. addFlaggedPath("-bootclasspath", bootclasspath, list);
  1328. addFlaggedPath("-extdirs", extdirs, list);
  1329. addFlaggedPath("-aspectpath", aspectpath, list);
  1330. addFlaggedPath("-injars", injars, list);
  1331. addFlaggedPath("-inpath", inpath, list);
  1332. addFlaggedPath("-sourceroots", sourceRoots, list);
  1333. if (argfiles != null) {
  1334. String[] files = argfiles.list();
  1335. for (int i = 0; i < files.length; i++) {
  1336. File argfile = project.resolveFile(files[i]);
  1337. if (check(argfile, files[i], false, location)) {
  1338. list.add("-argfile");
  1339. list.add(argfile.getAbsolutePath());
  1340. }
  1341. }
  1342. }
  1343. if (inxmlfiles != null) {
  1344. String[] files = inxmlfiles.list();
  1345. for (int i = 0; i < files.length; i++) {
  1346. File inxmlfile = project.resolveFile(files[i]);
  1347. if (check(inxmlfile, files[i], false, location)) {
  1348. list.add("-xmlConfigured");
  1349. list.add(inxmlfile.getAbsolutePath());
  1350. }
  1351. }
  1352. }
  1353. if (srcdir != null) {
  1354. // todo: ignore any srcdir if any argfiles and no explicit includes
  1355. String[] dirs = srcdir.list();
  1356. for (int i = 0; i < dirs.length; i++) {
  1357. File dir = project.resolveFile(dirs[i]);
  1358. check(dir, dirs[i], true, location);
  1359. // relies on compiler to prune non-source files
  1360. String[] files = getDirectoryScanner(dir).getIncludedFiles();
  1361. for (int j = 0; j < files.length; j++) {
  1362. File file = new File(dir, files[j]);
  1363. if (FileUtil.hasSourceSuffix(file)) {
  1364. if (!list.contains(file.getAbsolutePath())) {
  1365. list.add(file.getAbsolutePath());
  1366. }
  1367. }
  1368. }
  1369. }
  1370. }
  1371. if (0 < adapterFiles.size()) {
  1372. for (Iterator iter = adapterFiles.iterator(); iter.hasNext();) {
  1373. File file = (File) iter.next();
  1374. if (file.canRead() && FileUtil.hasSourceSuffix(file)) {
  1375. list.add(file.getAbsolutePath());
  1376. } else {
  1377. this.logger.warning("skipping file: " + file);
  1378. }
  1379. }
  1380. }
  1381. }
  1382. /**
  1383. * Throw BuildException unless file is valid.
  1384. *
  1385. * @param file the File to check
  1386. * @param name the symbolic name to print on error
  1387. * @param isDir if true, verify file is a directory
  1388. * @param loc the Location used to create sensible BuildException
  1389. * @return
  1390. * @throws BuildException unless file valid
  1391. */
  1392. protected final boolean check(File file, String name, boolean isDir, Location loc) {
  1393. loc = loc != null ? loc : location;
  1394. if (file == null) {
  1395. throw new BuildException(name + " is null!", loc);
  1396. }
  1397. if (!file.exists()) {
  1398. throw new BuildException(file + " doesn't exist!", loc);
  1399. }
  1400. if (isDir ^ file.isDirectory()) {
  1401. String e = file + " should" + (isDir ? "" : "n't") + " be a directory!";
  1402. throw new BuildException(e, loc);
  1403. }
  1404. return true;
  1405. }
  1406. /**
  1407. * Called when compile or incremental compile is completing, this completes the output jar or directory by copying resources if
  1408. * requested. Note: this is a callback run synchronously by the compiler. That means exceptions thrown here are caught by
  1409. * Main.run(..) and passed to the message handler.
  1410. */
  1411. protected void doCompletionTasks() {
  1412. if (!executing) {
  1413. throw new IllegalStateException("should be executing");
  1414. }
  1415. if (null != outjar) {
  1416. completeOutjar();
  1417. } else {
  1418. completeDestdir();
  1419. }
  1420. if (null != xdoneSignal) {
  1421. MessageUtil.info(messageHolder, xdoneSignal);
  1422. }
  1423. }
  1424. /**
  1425. * Complete the destination directory by copying resources from the source root directories (if the filter is specified) and
  1426. * non-.class files from the input jars (if XCopyInjars is enabled).
  1427. */
  1428. private void completeDestdir() {
  1429. if (!copyInjars && (null == sourceRootCopyFilter) && (null == inpathDirCopyFilter)) {
  1430. return;
  1431. } else if ((destDir == DEFAULT_DESTDIR) || !destDir.canWrite()) {
  1432. String s = "unable to copy resources to destDir: " + destDir;
  1433. throw new BuildException(s);
  1434. }
  1435. final Project project = getProject();
  1436. if (copyInjars) { // XXXX remove as unused since 1.1.1
  1437. if (null != inpath) {
  1438. log("copyInjars does not support inpath.\n", Project.MSG_WARN);
  1439. }
  1440. String taskName = getTaskName() + " - unzip";
  1441. String[] paths = injars.list();
  1442. if (!LangUtil.isEmpty(paths)) {
  1443. PatternSet patternSet = new PatternSet();
  1444. patternSet.setProject(project);
  1445. patternSet.setIncludes("**/*");
  1446. patternSet.setExcludes("**/*.class");
  1447. for (int i = 0; i < paths.length; i++) {
  1448. Expand unzip = new Expand();
  1449. unzip.setProject(project);
  1450. unzip.setTaskName(taskName);
  1451. unzip.setDest(destDir);
  1452. unzip.setSrc(new File(paths[i]));
  1453. unzip.addPatternset(patternSet);
  1454. unzip.execute();
  1455. }
  1456. }
  1457. }
  1458. if ((null != sourceRootCopyFilter) && (null != sourceRoots)) {
  1459. String[] paths = sourceRoots.list();
  1460. if (!LangUtil.isEmpty(paths)) {
  1461. Copy copy = new Copy();
  1462. copy.setProject(project);
  1463. copy.setTodir(destDir);
  1464. for (int i = 0; i < paths.length; i++) {
  1465. FileSet fileSet = new FileSet();
  1466. fileSet.setDir(new File(paths[i]));
  1467. fileSet.setIncludes("**/*");
  1468. fileSet.setExcludes(sourceRootCopyFilter);
  1469. copy.addFileset(fileSet);
  1470. }
  1471. copy.execute();
  1472. }
  1473. }
  1474. if ((null != inpathDirCopyFilter) && (null != inpath)) {
  1475. String[] paths = inpath.list();
  1476. if (!LangUtil.isEmpty(paths)) {
  1477. Copy copy = new Copy();
  1478. copy.setProject(project);
  1479. copy.setTodir(destDir);
  1480. boolean gotDir = false;
  1481. for (int i = 0; i < paths.length; i++) {
  1482. File inpathDir = new File(paths[i]);
  1483. if (inpathDir.isDirectory() && inpathDir.canRead()) {
  1484. if (!gotDir) {
  1485. gotDir = true;
  1486. }
  1487. FileSet fileSet = new FileSet();
  1488. fileSet.setDir(inpathDir);
  1489. fileSet.setIncludes("**/*");
  1490. fileSet.setExcludes(inpathDirCopyFilter);
  1491. copy.addFileset(fileSet);
  1492. }
  1493. }
  1494. if (gotDir) {
  1495. copy.execute();
  1496. }
  1497. }
  1498. }
  1499. }
  1500. /**
  1501. * Complete the output jar by copying resources from the source root directories if the filter is specified. and non-.class
  1502. * files from the input jars if enabled.
  1503. */
  1504. private void completeOutjar() {
  1505. if (((null == tmpOutjar) || !tmpOutjar.canRead())
  1506. || (!copyInjars && (null == sourceRootCopyFilter) && (null == inpathDirCopyFilter))) {
  1507. return;
  1508. }
  1509. Zip zip = new Zip();
  1510. Project project = getProject();
  1511. zip.setProject(project);
  1512. zip.setTaskName(getTaskName() + " - zip");
  1513. zip.setDestFile(outjar);
  1514. ZipFileSet zipfileset = new ZipFileSet();
  1515. zipfileset.setProject(project);
  1516. zipfileset.setSrc(tmpOutjar);
  1517. zipfileset.setIncludes("**/*.class");
  1518. zip.addZipfileset(zipfileset);
  1519. if (copyInjars) {
  1520. String[] paths = injars.list();
  1521. if (!LangUtil.isEmpty(paths)) {
  1522. for (int i = 0; i < paths.length; i++) {
  1523. File jarFile = new File(paths[i]);
  1524. zipfileset = new ZipFileSet();
  1525. zipfileset.setProject(project);
  1526. zipfileset.setSrc(jarFile);
  1527. zipfileset.setIncludes("**/*");
  1528. zipfileset.setExcludes("**/*.class");
  1529. zip.addZipfileset(zipfileset);
  1530. }
  1531. }
  1532. }
  1533. if ((null != sourceRootCopyFilter) && (null != sourceRoots)) {
  1534. String[] paths = sourceRoots.list();
  1535. if (!LangUtil.isEmpty(paths)) {
  1536. for (int i = 0; i < paths.length; i++) {
  1537. File srcRoot = new File(paths[i]);
  1538. FileSet fileset = new FileSet();
  1539. fileset.setProject(project);
  1540. fileset.setDir(srcRoot);
  1541. fileset.setIncludes("**/*");
  1542. fileset.setExcludes(sourceRootCopyFilter);
  1543. zip.addFileset(fileset);
  1544. }
  1545. }
  1546. }
  1547. if ((null != inpathDirCopyFilter) && (null != inpath)) {
  1548. String[] paths = inpath.list();
  1549. if (!LangUtil.isEmpty(paths)) {
  1550. for (int i = 0; i < paths.length; i++) {
  1551. File inpathDir = new File(paths[i]);
  1552. if (inpathDir.isDirectory() && inpathDir.canRead()) {
  1553. FileSet fileset = new FileSet();
  1554. fileset.setProject(project);
  1555. fileset.setDir(inpathDir);
  1556. fileset.setIncludes("**/*");
  1557. fileset.setExcludes(inpathDirCopyFilter);
  1558. zip.addFileset(fileset);
  1559. }
  1560. }
  1561. }
  1562. }
  1563. zip.execute();
  1564. }
  1565. // -------------------------- compiler adapter interface extras
  1566. /**
  1567. * Add specified source files.
  1568. */
  1569. void addFiles(File[] paths) {
  1570. for (int i = 0; i < paths.length; i++) {
  1571. addFile(paths[i]);
  1572. }
  1573. }
  1574. /**
  1575. * Add specified source file.
  1576. */
  1577. void addFile(File path) {
  1578. if (null != path) {
  1579. adapterFiles.add(path);
  1580. }
  1581. }
  1582. /**
  1583. * Read arguments in as if from a command line, mainly to support compiler adapter compilerarg subelement.
  1584. *
  1585. * @param args the String[] of arguments to read
  1586. */
  1587. public void readArguments(String[] args) { // XXX slow, stupid, unmaintainable
  1588. if ((null == args) || (0 == args.length)) {
  1589. return;
  1590. }
  1591. /** String[] wrapper with increment, error reporting */
  1592. class Args {
  1593. final String[] args;
  1594. int index = 0;
  1595. Args(String[] args) {
  1596. this.args = args; // not null or empty
  1597. }
  1598. boolean hasNext() {
  1599. return index < args.length;
  1600. }
  1601. String next() {
  1602. String err = null;
  1603. if (!hasNext()) {
  1604. err = "need arg for flag " + args[args.length - 1];
  1605. } else {
  1606. String s = args[index++];
  1607. if (null == s) {
  1608. err = "null value";
  1609. } else {
  1610. s = s.trim();
  1611. if (0 == s.trim().length()) {
  1612. err = "no value";
  1613. } else {
  1614. return s;
  1615. }
  1616. }
  1617. }
  1618. err += " at [" + index + "] of " + Arrays.asList(args);
  1619. throw new BuildException(err);
  1620. }
  1621. } // class Args
  1622. Args in = new Args(args);
  1623. String flag;
  1624. while (in.hasNext()) {
  1625. flag = in.next();
  1626. if ("-1.3".equals(flag)) {
  1627. setCompliance(flag);
  1628. } else if ("-1.4".equals(flag)) {
  1629. setCompliance(flag);
  1630. } else if ("-1.5".equals(flag)) {
  1631. setCompliance("1.5");
  1632. } else if ("-argfile".equals(flag)) {
  1633. setArgfiles(new Path(project, in.next()));
  1634. } else if ("-aspectpath".equals(flag)) {
  1635. setAspectpath(new Path(project, in.next()));
  1636. } else if ("-classpath".equals(flag)) {
  1637. setClasspath(new Path(project, in.next()));
  1638. } else if ("-extdirs".equals(flag)) {
  1639. setExtdirs(new Path(project, in.next()));
  1640. } else if ("-Xcopyinjars".equals(flag)) {
  1641. setCopyInjars(true); // ignored - will be flagged by setter
  1642. } else if ("-g".equals(flag)) {
  1643. setDebug(true);
  1644. } else if (flag.startsWith("-g:")) {
  1645. setDebugLevel(flag.substring(2));
  1646. } else if ("-deprecation".equals(flag)) {
  1647. setDeprecation(true);
  1648. } else if ("-d".equals(flag)) {
  1649. setDestdir(new File(in.next()));
  1650. } else if ("-crossrefs".equals(flag)) {
  1651. setCrossrefs(true);
  1652. } else if ("-emacssym".equals(flag)) {
  1653. setEmacssym(true);
  1654. } else if ("-encoding".equals(flag)) {
  1655. setEncoding(in.next());
  1656. } else if ("-Xfailonerror".equals(flag)) {
  1657. setFailonerror(true);
  1658. } else if ("-fork".equals(flag)) {
  1659. setFork(true);
  1660. } else if ("-forkclasspath".equals(flag)) {
  1661. setForkclasspath(new Path(project, in.next()));
  1662. } else if ("-help".equals(flag)) {
  1663. setHelp(true);
  1664. } else if ("-incremental".equals(flag)) {
  1665. setIncremental(true);
  1666. } else if ("-injars".equals(flag)) {
  1667. setInjars(new Path(project, in.next()));
  1668. } else if ("-inpath".equals(flag)) {
  1669. setInpath(new Path(project, in.next()));
  1670. } else if ("-Xlistfileargs".equals(flag)) {
  1671. setListFileArgs(true);
  1672. } else if ("-Xmaxmem".equals(flag)) {
  1673. setMaxmem(in.next());
  1674. } else if ("-Xmessageholderclass".equals(flag)) {
  1675. setMessageHolderClass(in.next());
  1676. } else if ("-noexit".equals(flag)) {
  1677. setNoExit(true);
  1678. } else if ("-noimport".equals(flag)) {
  1679. setNoExit(true);
  1680. } else if ("-noExit".equals(flag)) {
  1681. setNoExit(true);
  1682. } else if ("-noImportError".equals(flag)) {
  1683. setNoImportError(true);
  1684. } else if ("-noWarn".equals(flag)) {
  1685. setNowarn(true);
  1686. } else if ("-noexit".equals(flag)) {
  1687. setNoExit(true);
  1688. } else if ("-outjar".equals(flag)) {
  1689. setOutjar(new File(in.next()));
  1690. } else if ("-outxml".equals(flag)) {
  1691. setOutxml(true);
  1692. } else if ("-outxmlfile".equals(flag)) {
  1693. setOutxmlfile(in.next());
  1694. } else if ("-preserveAllLocals".equals(flag)) {
  1695. setPreserveAllLocals(true);
  1696. } else if ("-proceedOnError".equals(flag)) {
  1697. setProceedOnError(true);
  1698. } else if ("-referenceInfo".equals(flag)) {
  1699. setReferenceInfo(true);
  1700. } else if ("-source".equals(flag)) {
  1701. setSource(in.next());
  1702. } else if ("-Xsourcerootcopyfilter".equals(flag)) {
  1703. setSourceRootCopyFilter(in.next());
  1704. } else if ("-sourceroots".equals(flag)) {
  1705. setSourceRoots(new Path(project, in.next()));
  1706. } else if ("-Xsrcdir".equals(flag)) {
  1707. setSrcDir(new Path(project, in.next()));
  1708. } else if ("-Xtagfile".equals(flag)) {
  1709. setTagFile(new File(in.next()));
  1710. } else if ("-target".equals(flag)) {
  1711. setTarget(in.next());
  1712. } else if ("-time".equals(flag)) {
  1713. setTime(true);
  1714. } else if ("-time".equals(flag)) {
  1715. setTime(true);
  1716. } else if ("-verbose".equals(flag)) {
  1717. setVerbose(true);
  1718. } else if ("-showWeaveInfo".equals(flag)) {
  1719. setShowWeaveInfo(true);
  1720. } else if ("-version".equals(flag)) {
  1721. setVersion(true);
  1722. } else if ("-warn".equals(flag)) {
  1723. setWarn(in.next());
  1724. } else if (flag.startsWith("-warn:")) {
  1725. setWarn(flag.substring(6));
  1726. } else if ("-Xlint".equals(flag)) {
  1727. setXlintwarnings(true);
  1728. } else if (flag.startsWith("-Xlint:")) {
  1729. setXlint(flag.substring(7));
  1730. } else if ("-Xlintfile".equals(flag)) {
  1731. setXlintfile(new File(in.next()));
  1732. } else if ("-XterminateAfterCompilation".equals(flag)) {
  1733. setXTerminateAfterCompilation(true);
  1734. } else if ("-Xreweavable".equals(flag)) {
  1735. setXReweavable(true);
  1736. } else if ("-XnotReweavable".equals(flag)) {
  1737. setXNotReweavable(true);
  1738. } else if (flag.startsWith("@")) {
  1739. File file = new File(flag.substring(1));
  1740. if (file.canRead()) {
  1741. setArgfiles(new Path(project, file.getPath()));
  1742. } else {
  1743. ignore(flag);
  1744. }
  1745. } else {
  1746. File file = new File(flag);
  1747. if (file.isFile() && file.canRead() && FileUtil.hasSourceSuffix(file)) {
  1748. addFile(file);
  1749. } else {
  1750. ignore(flag);
  1751. }
  1752. }
  1753. }
  1754. }
  1755. protected void logVerbose(String text) {
  1756. if (this.verbose) {
  1757. this.logger.info(text);
  1758. } else {
  1759. this.logger.verbose(text);
  1760. }
  1761. }
  1762. /**
  1763. * Commandline wrapper that only permits addition of non-empty values and converts to argfile form if necessary.
  1764. */
  1765. public static class GuardedCommand {
  1766. Commandline command;
  1767. // int size;
  1768. static boolean isEmpty(String s) {
  1769. return ((null == s) || (0 == s.trim().length()));
  1770. }
  1771. GuardedCommand() {
  1772. command = new Commandline();
  1773. }
  1774. void addFlag(String flag, boolean doAdd) {
  1775. if (doAdd && !isEmpty(flag)) {
  1776. command.createArgument().setValue(flag);
  1777. // size += 1 + flag.length();
  1778. }
  1779. }
  1780. /** @return null if added or ignoreString otherwise */
  1781. String addOption(String prefix, String[] validOptions, String input) {
  1782. if (isEmpty(input)) {
  1783. return null;
  1784. }
  1785. for (int i = 0; i < validOptions.length; i++) {
  1786. if (input.equals(validOptions[i])) {
  1787. if (isEmpty(prefix)) {
  1788. addFlag(input, true);
  1789. } else {
  1790. addFlagged(prefix, input);
  1791. }
  1792. return null;
  1793. }
  1794. }
  1795. return (null == prefix ? input : prefix + " " + input);
  1796. }
  1797. void addFlagged(String flag, String argument) {
  1798. if (!isEmpty(flag) && !isEmpty(argument)) {
  1799. command.addArguments(new String[] { flag, argument });
  1800. // size += 1 + flag.length() + argument.length();
  1801. }
  1802. }
  1803. // private void addFile(File file) {
  1804. // if (null != file) {
  1805. // String path = file.getAbsolutePath();
  1806. // addFlag(path, true);
  1807. // }
  1808. // }
  1809. List extractArguments() {
  1810. ArrayList result = new ArrayList();
  1811. String[] cmds = command.getArguments();
  1812. if (!LangUtil.isEmpty(cmds)) {
  1813. result.addAll(Arrays.asList(cmds));
  1814. }
  1815. return result;
  1816. }
  1817. /**
  1818. * Adjust args for size if necessary by creating an argument file, which should be deleted by the client after the compiler
  1819. * run has completed.
  1820. *
  1821. * @param max the int maximum length of the command line (in char)
  1822. * @return the temp File for the arguments (if generated), for deletion when done.
  1823. * @throws IllegalArgumentException if max is negative
  1824. */
  1825. static String[] limitTo(String[] args, int max, Location location) {
  1826. if (max < 0) {
  1827. throw new IllegalArgumentException("negative max: " + max);
  1828. }
  1829. // sigh - have to count anyway for now
  1830. int size = 0;
  1831. for (int i = 0; (i < args.length) && (size < max); i++) {
  1832. size += 1 + (null == args[i] ? 0 : args[i].length());
  1833. }
  1834. if (size <= max) {
  1835. return args;
  1836. }
  1837. File tmpFile = null;
  1838. PrintWriter out = null;
  1839. // adapted from DefaultCompilerAdapter.executeExternalCompile
  1840. try {
  1841. String userDirName = System.getProperty("user.dir");
  1842. File userDir = new File(userDirName);
  1843. tmpFile = File.createTempFile("argfile", "", userDir);
  1844. out = new PrintWriter(new FileWriter(tmpFile));
  1845. for (int i = 0; i < args.length; i++) {
  1846. out.println(args[i]);
  1847. }
  1848. out.flush();
  1849. return new String[] { "-argfile", tmpFile.getAbsolutePath() };
  1850. } catch (IOException e) {
  1851. throw new BuildException("Error creating temporary file", e, location);
  1852. } finally {
  1853. if (out != null) {
  1854. try {
  1855. out.close();
  1856. } catch (Throwable t) {
  1857. }
  1858. }
  1859. }
  1860. }
  1861. }
  1862. private static class AntMessageHandler implements IMessageHandler {
  1863. private TaskLogger logger;
  1864. private final boolean taskLevelVerbose;
  1865. private final boolean handledMessage;
  1866. public AntMessageHandler(TaskLogger logger, boolean taskVerbose, boolean handledMessage) {
  1867. this.logger = logger;
  1868. this.taskLevelVerbose = taskVerbose;
  1869. this.handledMessage = handledMessage;
  1870. }
  1871. /*
  1872. * (non-Javadoc)
  1873. *
  1874. * @see org.aspectj.bridge.IMessageHandler#handleMessage(org.aspectj.bridge.IMessage)
  1875. */
  1876. public boolean handleMessage(IMessage message) throws AbortException {
  1877. Kind messageKind = message.getKind();
  1878. String messageText = message.toString();
  1879. if (messageKind == IMessage.ABORT) {
  1880. this.logger.error(messageText);
  1881. } else if (messageKind == IMessage.DEBUG) {
  1882. this.logger.debug(messageText);
  1883. } else if (messageKind == IMessage.ERROR) {
  1884. this.logger.error(messageText);
  1885. } else if (messageKind == IMessage.FAIL) {
  1886. this.logger.error(messageText);
  1887. } else if (messageKind == IMessage.INFO) {
  1888. if (this.taskLevelVerbose) {
  1889. this.logger.info(messageText);
  1890. } else {
  1891. this.logger.verbose(messageText);
  1892. }
  1893. } else if (messageKind == IMessage.WARNING) {
  1894. this.logger.warning(messageText);
  1895. } else if (messageKind == IMessage.WEAVEINFO) {
  1896. this.logger.info(messageText);
  1897. } else if (messageKind == IMessage.TASKTAG) {
  1898. // ignore
  1899. } else {
  1900. throw new BuildException("Unknown message kind from AspectJ compiler: " + messageKind.toString());
  1901. }
  1902. return handledMessage;
  1903. }
  1904. /*
  1905. * (non-Javadoc)
  1906. *
  1907. * @see org.aspectj.bridge.IMessageHandler#isIgnoring(org.aspectj.bridge.IMessage.Kind)
  1908. */
  1909. public boolean isIgnoring(Kind kind) {
  1910. return false;
  1911. }
  1912. /*
  1913. * (non-Javadoc)
  1914. *
  1915. * @see org.aspectj.bridge.IMessageHandler#dontIgnore(org.aspectj.bridge.IMessage.Kind)
  1916. */
  1917. public void dontIgnore(Kind kind) {
  1918. }
  1919. /*
  1920. * (non-Javadoc)
  1921. *
  1922. * @see org.aspectj.bridge.IMessageHandler#ignore(org.aspectj.bridge.IMessage.Kind)
  1923. */
  1924. public void ignore(Kind kind) {
  1925. }
  1926. }
  1927. }