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 64KB

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