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

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