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

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164
  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 v 2.0
  8. * which accompanies this distribution and is available at
  9. * https://www.eclipse.org/org/documents/epl-2.0/EPL-2.0.txt
  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<String> VALID_XOPTIONS;
  225. /** valid warning (-warn:[...]) variants */
  226. private static final List<String> VALID_WARNINGS;
  227. /** valid debugging (-g:[...]) variants */
  228. private static final List<String> VALID_DEBUG;
  229. /**
  230. * -Xlint variants (error, warning, ignore)
  231. *
  232. * @see org.aspectj.weaver.Lint
  233. */
  234. private static final List<String> 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", "15", "16", "17" };
  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", "15", "16", "17" };
  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", "-15", "-16", "-17" };
  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.getDeclaredConstructor().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<String> 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. StringBuilder result = new StringBuilder();
  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.getDeclaredConstructor().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.getDeclaredConstructor().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<String> 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. StringBuilder sb = new StringBuilder();
  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. StringBuilder sb = new StringBuilder();
  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 (File file : adapterFiles) {
  1394. if (file.canRead() && FileUtil.hasSourceSuffix(file)) {
  1395. list.add(file.getAbsolutePath());
  1396. }
  1397. else {
  1398. this.logger.warning("skipping file: " + file);
  1399. }
  1400. }
  1401. }
  1402. }
  1403. /**
  1404. * Throw BuildException unless file is valid.
  1405. *
  1406. * @param file the File to check
  1407. * @param name the symbolic name to print on error
  1408. * @param isDir if true, verify file is a directory
  1409. * @param loc the Location used to create sensible BuildException
  1410. * @return
  1411. * @throws BuildException unless file valid
  1412. */
  1413. protected final boolean check(File file, String name, boolean isDir, Location loc) {
  1414. loc = loc != null ? loc : location;
  1415. if (file == null) {
  1416. throw new BuildException(name + " is null!", loc);
  1417. }
  1418. if (!file.exists()) {
  1419. throw new BuildException(file + " doesn't exist!", loc);
  1420. }
  1421. if (isDir ^ file.isDirectory()) {
  1422. String e = file + " should" + (isDir ? "" : "n't") + " be a directory!";
  1423. throw new BuildException(e, loc);
  1424. }
  1425. return true;
  1426. }
  1427. /**
  1428. * Called when compile or incremental compile is completing, this completes the output jar or directory by copying resources if
  1429. * requested. Note: this is a callback run synchronously by the compiler. That means exceptions thrown here are caught by
  1430. * Main.run(..) and passed to the message handler.
  1431. */
  1432. protected void doCompletionTasks() {
  1433. if (!executing) {
  1434. throw new IllegalStateException("should be executing");
  1435. }
  1436. if (null != outjar) {
  1437. completeOutjar();
  1438. } else {
  1439. completeDestdir();
  1440. }
  1441. if (null != xdoneSignal) {
  1442. MessageUtil.info(messageHolder, xdoneSignal);
  1443. }
  1444. }
  1445. /**
  1446. * Complete the destination directory by copying resources from the source root directories (if the filter is specified) and
  1447. * non-.class files from the input jars (if XCopyInjars is enabled).
  1448. */
  1449. private void completeDestdir() {
  1450. if (!copyInjars && (null == sourceRootCopyFilter) && (null == inpathDirCopyFilter)) {
  1451. return;
  1452. } else if ((destDir == DEFAULT_DESTDIR) || !destDir.canWrite()) {
  1453. String s = "unable to copy resources to destDir: " + destDir;
  1454. throw new BuildException(s);
  1455. }
  1456. final Project project = getProject();
  1457. if (copyInjars) { // XXXX remove as unused since 1.1.1
  1458. if (null != inpath) {
  1459. log("copyInjars does not support inpath.\n", Project.MSG_WARN);
  1460. }
  1461. String taskName = getTaskName() + " - unzip";
  1462. String[] paths = injars.list();
  1463. if (!LangUtil.isEmpty(paths)) {
  1464. PatternSet patternSet = new PatternSet();
  1465. patternSet.setProject(project);
  1466. patternSet.setIncludes("**/*");
  1467. patternSet.setExcludes("**/*.class");
  1468. for (String path : paths) {
  1469. Expand unzip = new Expand();
  1470. unzip.setProject(project);
  1471. unzip.setTaskName(taskName);
  1472. unzip.setDest(destDir);
  1473. unzip.setSrc(new File(path));
  1474. unzip.addPatternset(patternSet);
  1475. unzip.execute();
  1476. }
  1477. }
  1478. }
  1479. if ((null != sourceRootCopyFilter) && (null != sourceRoots)) {
  1480. String[] paths = sourceRoots.list();
  1481. if (!LangUtil.isEmpty(paths)) {
  1482. Copy copy = new Copy();
  1483. copy.setProject(project);
  1484. copy.setTodir(destDir);
  1485. for (String path : paths) {
  1486. FileSet fileSet = new FileSet();
  1487. fileSet.setDir(new File(path));
  1488. fileSet.setIncludes("**/*");
  1489. fileSet.setExcludes(sourceRootCopyFilter);
  1490. copy.addFileset(fileSet);
  1491. }
  1492. copy.execute();
  1493. }
  1494. }
  1495. if ((null != inpathDirCopyFilter) && (null != inpath)) {
  1496. String[] paths = inpath.list();
  1497. if (!LangUtil.isEmpty(paths)) {
  1498. Copy copy = new Copy();
  1499. copy.setProject(project);
  1500. copy.setTodir(destDir);
  1501. boolean gotDir = false;
  1502. for (String path : paths) {
  1503. File inpathDir = new File(path);
  1504. if (inpathDir.isDirectory() && inpathDir.canRead()) {
  1505. if (!gotDir) {
  1506. gotDir = true;
  1507. }
  1508. FileSet fileSet = new FileSet();
  1509. fileSet.setDir(inpathDir);
  1510. fileSet.setIncludes("**/*");
  1511. fileSet.setExcludes(inpathDirCopyFilter);
  1512. copy.addFileset(fileSet);
  1513. }
  1514. }
  1515. if (gotDir) {
  1516. copy.execute();
  1517. }
  1518. }
  1519. }
  1520. }
  1521. /**
  1522. * Complete the output jar by copying resources from the source root directories if the filter is specified. and non-.class
  1523. * files from the input jars if enabled.
  1524. */
  1525. private void completeOutjar() {
  1526. if (((null == tmpOutjar) || !tmpOutjar.canRead())
  1527. || (!copyInjars && (null == sourceRootCopyFilter) && (null == inpathDirCopyFilter))) {
  1528. return;
  1529. }
  1530. Zip zip = new Zip();
  1531. Project project = getProject();
  1532. zip.setProject(project);
  1533. zip.setTaskName(getTaskName() + " - zip");
  1534. zip.setDestFile(outjar);
  1535. ZipFileSet zipfileset = new ZipFileSet();
  1536. zipfileset.setProject(project);
  1537. zipfileset.setSrc(tmpOutjar);
  1538. zipfileset.setIncludes("**/*.class");
  1539. zip.addZipfileset(zipfileset);
  1540. if (copyInjars) {
  1541. String[] paths = injars.list();
  1542. if (!LangUtil.isEmpty(paths)) {
  1543. for (String path : paths) {
  1544. File jarFile = new File(path);
  1545. zipfileset = new ZipFileSet();
  1546. zipfileset.setProject(project);
  1547. zipfileset.setSrc(jarFile);
  1548. zipfileset.setIncludes("**/*");
  1549. zipfileset.setExcludes("**/*.class");
  1550. zip.addZipfileset(zipfileset);
  1551. }
  1552. }
  1553. }
  1554. if ((null != sourceRootCopyFilter) && (null != sourceRoots)) {
  1555. String[] paths = sourceRoots.list();
  1556. if (!LangUtil.isEmpty(paths)) {
  1557. for (String path : paths) {
  1558. File srcRoot = new File(path);
  1559. FileSet fileset = new FileSet();
  1560. fileset.setProject(project);
  1561. fileset.setDir(srcRoot);
  1562. fileset.setIncludes("**/*");
  1563. fileset.setExcludes(sourceRootCopyFilter);
  1564. zip.addFileset(fileset);
  1565. }
  1566. }
  1567. }
  1568. if ((null != inpathDirCopyFilter) && (null != inpath)) {
  1569. String[] paths = inpath.list();
  1570. if (!LangUtil.isEmpty(paths)) {
  1571. for (String path : paths) {
  1572. File inpathDir = new File(path);
  1573. if (inpathDir.isDirectory() && inpathDir.canRead()) {
  1574. FileSet fileset = new FileSet();
  1575. fileset.setProject(project);
  1576. fileset.setDir(inpathDir);
  1577. fileset.setIncludes("**/*");
  1578. fileset.setExcludes(inpathDirCopyFilter);
  1579. zip.addFileset(fileset);
  1580. }
  1581. }
  1582. }
  1583. }
  1584. zip.execute();
  1585. }
  1586. // -------------------------- compiler adapter interface extras
  1587. /**
  1588. * Add specified source files.
  1589. */
  1590. void addFiles(File[] paths) {
  1591. for (File path : paths) {
  1592. addFile(path);
  1593. }
  1594. }
  1595. /**
  1596. * Add specified source file.
  1597. */
  1598. void addFile(File path) {
  1599. if (null != path) {
  1600. adapterFiles.add(path);
  1601. }
  1602. }
  1603. /**
  1604. * Read arguments in as if from a command line, mainly to support compiler adapter compilerarg subelement.
  1605. *
  1606. * @param args the String[] of arguments to read
  1607. */
  1608. public void readArguments(String[] args) { // XXX slow, stupid, unmaintainable
  1609. if ((null == args) || (0 == args.length)) {
  1610. return;
  1611. }
  1612. /** String[] wrapper with increment, error reporting */
  1613. class Args {
  1614. final String[] args;
  1615. int index = 0;
  1616. Args(String[] args) {
  1617. this.args = args; // not null or empty
  1618. }
  1619. boolean hasNext() {
  1620. return index < args.length;
  1621. }
  1622. String next() {
  1623. String err = null;
  1624. if (!hasNext()) {
  1625. err = "need arg for flag " + args[args.length - 1];
  1626. } else {
  1627. String s = args[index++];
  1628. if (null == s) {
  1629. err = "null value";
  1630. } else {
  1631. s = s.trim();
  1632. if (0 == s.trim().length()) {
  1633. err = "no value";
  1634. } else {
  1635. return s;
  1636. }
  1637. }
  1638. }
  1639. err += " at [" + index + "] of " + Arrays.asList(args);
  1640. throw new BuildException(err);
  1641. }
  1642. } // class Args
  1643. Args in = new Args(args);
  1644. String flag;
  1645. while (in.hasNext()) {
  1646. flag = in.next();
  1647. if ("-1.3".equals(flag)) {
  1648. setCompliance(flag);
  1649. } else if ("-1.4".equals(flag)) {
  1650. setCompliance(flag);
  1651. } else if ("-1.5".equals(flag)) {
  1652. setCompliance("1.5");
  1653. } else if ("-argfile".equals(flag)) {
  1654. setArgfiles(new Path(project, in.next()));
  1655. } else if ("-aspectpath".equals(flag)) {
  1656. setAspectpath(new Path(project, in.next()));
  1657. } else if ("-classpath".equals(flag)) {
  1658. setClasspath(new Path(project, in.next()));
  1659. } else if ("-extdirs".equals(flag)) {
  1660. setExtdirs(new Path(project, in.next()));
  1661. } else if ("-Xcopyinjars".equals(flag)) {
  1662. setCopyInjars(true); // ignored - will be flagged by setter
  1663. } else if ("-g".equals(flag)) {
  1664. setDebug(true);
  1665. } else if (flag.startsWith("-g:")) {
  1666. setDebugLevel(flag.substring(2));
  1667. } else if ("-deprecation".equals(flag)) {
  1668. setDeprecation(true);
  1669. } else if ("-d".equals(flag)) {
  1670. setDestdir(new File(in.next()));
  1671. } else if ("-crossrefs".equals(flag)) {
  1672. setCrossrefs(true);
  1673. } else if ("-emacssym".equals(flag)) {
  1674. setEmacssym(true);
  1675. } else if ("-encoding".equals(flag)) {
  1676. setEncoding(in.next());
  1677. } else if ("-Xfailonerror".equals(flag)) {
  1678. setFailonerror(true);
  1679. } else if ("-fork".equals(flag)) {
  1680. setFork(true);
  1681. } else if ("-forkclasspath".equals(flag)) {
  1682. setForkclasspath(new Path(project, in.next()));
  1683. } else if ("-help".equals(flag)) {
  1684. setHelp(true);
  1685. } else if ("-incremental".equals(flag)) {
  1686. setIncremental(true);
  1687. } else if ("-injars".equals(flag)) {
  1688. setInjars(new Path(project, in.next()));
  1689. } else if ("-inpath".equals(flag)) {
  1690. setInpath(new Path(project, in.next()));
  1691. } else if ("-Xlistfileargs".equals(flag)) {
  1692. setListFileArgs(true);
  1693. } else if ("-Xmaxmem".equals(flag)) {
  1694. setMaxmem(in.next());
  1695. } else if ("-Xmessageholderclass".equals(flag)) {
  1696. setMessageHolderClass(in.next());
  1697. } else if ("-noexit".equals(flag)) {
  1698. setNoExit(true);
  1699. } else if ("-noimport".equals(flag)) {
  1700. setNoExit(true);
  1701. } else if ("-noExit".equals(flag)) {
  1702. setNoExit(true);
  1703. } else if ("-noImportError".equals(flag)) {
  1704. setNoImportError(true);
  1705. } else if ("-noWarn".equals(flag)) {
  1706. setNowarn(true);
  1707. } else if ("-noexit".equals(flag)) {
  1708. setNoExit(true);
  1709. } else if ("-outjar".equals(flag)) {
  1710. setOutjar(new File(in.next()));
  1711. } else if ("-outxml".equals(flag)) {
  1712. setOutxml(true);
  1713. } else if ("-outxmlfile".equals(flag)) {
  1714. setOutxmlfile(in.next());
  1715. } else if ("-preserveAllLocals".equals(flag)) {
  1716. setPreserveAllLocals(true);
  1717. } else if ("-proceedOnError".equals(flag)) {
  1718. setProceedOnError(true);
  1719. } else if ("-referenceInfo".equals(flag)) {
  1720. setReferenceInfo(true);
  1721. } else if ("-source".equals(flag)) {
  1722. setSource(in.next());
  1723. } else if ("-Xsourcerootcopyfilter".equals(flag)) {
  1724. setSourceRootCopyFilter(in.next());
  1725. } else if ("-sourceroots".equals(flag)) {
  1726. setSourceRoots(new Path(project, in.next()));
  1727. } else if ("-Xsrcdir".equals(flag)) {
  1728. setSrcDir(new Path(project, in.next()));
  1729. } else if ("-Xtagfile".equals(flag)) {
  1730. setTagFile(new File(in.next()));
  1731. } else if ("-target".equals(flag)) {
  1732. setTarget(in.next());
  1733. } else if ("-time".equals(flag)) {
  1734. setTime(true);
  1735. } else if ("-time".equals(flag)) {
  1736. setTime(true);
  1737. } else if ("-verbose".equals(flag)) {
  1738. setVerbose(true);
  1739. } else if ("-showWeaveInfo".equals(flag)) {
  1740. setShowWeaveInfo(true);
  1741. } else if ("-version".equals(flag)) {
  1742. setVersion(true);
  1743. } else if ("-warn".equals(flag)) {
  1744. setWarn(in.next());
  1745. } else if (flag.startsWith("-warn:")) {
  1746. setWarn(flag.substring(6));
  1747. } else if ("-Xlint".equals(flag)) {
  1748. setXlintwarnings(true);
  1749. } else if (flag.startsWith("-Xlint:")) {
  1750. setXlint(flag.substring(7));
  1751. } else if ("-Xlintfile".equals(flag)) {
  1752. setXlintfile(new File(in.next()));
  1753. } else if ("-XterminateAfterCompilation".equals(flag)) {
  1754. setXTerminateAfterCompilation(true);
  1755. } else if ("-Xreweavable".equals(flag)) {
  1756. setXReweavable(true);
  1757. } else if ("-XnotReweavable".equals(flag)) {
  1758. setXNotReweavable(true);
  1759. } else if (flag.startsWith("@")) {
  1760. File file = new File(flag.substring(1));
  1761. if (file.canRead()) {
  1762. setArgfiles(new Path(project, file.getPath()));
  1763. } else {
  1764. ignore(flag);
  1765. }
  1766. } else {
  1767. File file = new File(flag);
  1768. if (file.isFile() && file.canRead() && FileUtil.hasSourceSuffix(file)) {
  1769. addFile(file);
  1770. } else {
  1771. ignore(flag);
  1772. }
  1773. }
  1774. }
  1775. }
  1776. protected void logVerbose(String text) {
  1777. if (this.verbose) {
  1778. this.logger.info(text);
  1779. } else {
  1780. this.logger.verbose(text);
  1781. }
  1782. }
  1783. /**
  1784. * Commandline wrapper that only permits addition of non-empty values and converts to argfile form if necessary.
  1785. */
  1786. public static class GuardedCommand {
  1787. Commandline command;
  1788. // int size;
  1789. static boolean isEmpty(String s) {
  1790. return ((null == s) || (0 == s.trim().length()));
  1791. }
  1792. GuardedCommand() {
  1793. command = new Commandline();
  1794. }
  1795. void addFlag(String flag, boolean doAdd) {
  1796. if (doAdd && !isEmpty(flag)) {
  1797. command.createArgument().setValue(flag);
  1798. // size += 1 + flag.length();
  1799. }
  1800. }
  1801. /** @return null if added or ignoreString otherwise */
  1802. String addOption(String prefix, String[] validOptions, String input) {
  1803. if (isEmpty(input)) {
  1804. return null;
  1805. }
  1806. for (String validOption : validOptions) {
  1807. if (input.equals(validOption)) {
  1808. if (isEmpty(prefix)) {
  1809. addFlag(input, true);
  1810. } else {
  1811. addFlagged(prefix, input);
  1812. }
  1813. return null;
  1814. }
  1815. }
  1816. return (null == prefix ? input : prefix + " " + input);
  1817. }
  1818. void addFlagged(String flag, String argument) {
  1819. if (!isEmpty(flag) && !isEmpty(argument)) {
  1820. command.addArguments(new String[] { flag, argument });
  1821. // size += 1 + flag.length() + argument.length();
  1822. }
  1823. }
  1824. // private void addFile(File file) {
  1825. // if (null != file) {
  1826. // String path = file.getAbsolutePath();
  1827. // addFlag(path, true);
  1828. // }
  1829. // }
  1830. List extractArguments() {
  1831. List<String> result = new ArrayList<>();
  1832. String[] cmds = command.getArguments();
  1833. if (!LangUtil.isEmpty(cmds)) {
  1834. result.addAll(Arrays.asList(cmds));
  1835. }
  1836. return result;
  1837. }
  1838. /**
  1839. * Adjust args for size if necessary by creating an argument file, which should be deleted by the client after the compiler
  1840. * run has completed.
  1841. *
  1842. * @param max the int maximum length of the command line (in char)
  1843. * @return the temp File for the arguments (if generated), for deletion when done.
  1844. * @throws IllegalArgumentException if max is negative
  1845. */
  1846. static String[] limitTo(String[] args, int max, Location location) {
  1847. if (max < 0) {
  1848. throw new IllegalArgumentException("negative max: " + max);
  1849. }
  1850. // sigh - have to count anyway for now
  1851. int size = 0;
  1852. for (int i = 0; (i < args.length) && (size < max); i++) {
  1853. size += 1 + (null == args[i] ? 0 : args[i].length());
  1854. }
  1855. if (size <= max) {
  1856. return args;
  1857. }
  1858. File tmpFile = null;
  1859. PrintWriter out = null;
  1860. // adapted from DefaultCompilerAdapter.executeExternalCompile
  1861. try {
  1862. String userDirName = System.getProperty("user.dir");
  1863. File userDir = new File(userDirName);
  1864. tmpFile = File.createTempFile("argfile", "", userDir);
  1865. out = new PrintWriter(new FileWriter(tmpFile));
  1866. for (String arg : args) {
  1867. out.println(arg);
  1868. }
  1869. out.flush();
  1870. return new String[] { "-argfile", tmpFile.getAbsolutePath() };
  1871. } catch (IOException e) {
  1872. throw new BuildException("Error creating temporary file", e, location);
  1873. } finally {
  1874. if (out != null) {
  1875. try {
  1876. out.close();
  1877. } catch (Throwable t) {
  1878. }
  1879. }
  1880. }
  1881. }
  1882. }
  1883. private static class AntMessageHandler implements IMessageHandler {
  1884. private TaskLogger logger;
  1885. private final boolean taskLevelVerbose;
  1886. private final boolean handledMessage;
  1887. public AntMessageHandler(TaskLogger logger, boolean taskVerbose, boolean handledMessage) {
  1888. this.logger = logger;
  1889. this.taskLevelVerbose = taskVerbose;
  1890. this.handledMessage = handledMessage;
  1891. }
  1892. /*
  1893. * (non-Javadoc)
  1894. *
  1895. * @see org.aspectj.bridge.IMessageHandler#handleMessage(org.aspectj.bridge.IMessage)
  1896. */
  1897. @Override
  1898. public boolean handleMessage(IMessage message) throws AbortException {
  1899. Kind messageKind = message.getKind();
  1900. String messageText = message.toString();
  1901. if (messageKind == IMessage.ABORT) {
  1902. this.logger.error(messageText);
  1903. } else if (messageKind == IMessage.DEBUG) {
  1904. this.logger.debug(messageText);
  1905. } else if (messageKind == IMessage.ERROR) {
  1906. this.logger.error(messageText);
  1907. } else if (messageKind == IMessage.FAIL) {
  1908. this.logger.error(messageText);
  1909. } else if (messageKind == IMessage.INFO) {
  1910. if (this.taskLevelVerbose) {
  1911. this.logger.info(messageText);
  1912. } else {
  1913. this.logger.verbose(messageText);
  1914. }
  1915. } else if (messageKind == IMessage.WARNING) {
  1916. this.logger.warning(messageText);
  1917. } else if (messageKind == IMessage.WEAVEINFO) {
  1918. this.logger.info(messageText);
  1919. } else if (messageKind == IMessage.TASKTAG) {
  1920. // ignore
  1921. } else {
  1922. throw new BuildException("Unknown message kind from AspectJ compiler: " + messageKind.toString());
  1923. }
  1924. return handledMessage;
  1925. }
  1926. /*
  1927. * (non-Javadoc)
  1928. *
  1929. * @see org.aspectj.bridge.IMessageHandler#isIgnoring(org.aspectj.bridge.IMessage.Kind)
  1930. */
  1931. @Override
  1932. public boolean isIgnoring(Kind kind) {
  1933. return false;
  1934. }
  1935. /*
  1936. * (non-Javadoc)
  1937. *
  1938. * @see org.aspectj.bridge.IMessageHandler#dontIgnore(org.aspectj.bridge.IMessage.Kind)
  1939. */
  1940. @Override
  1941. public void dontIgnore(Kind kind) {
  1942. }
  1943. /*
  1944. * (non-Javadoc)
  1945. *
  1946. * @see org.aspectj.bridge.IMessageHandler#ignore(org.aspectj.bridge.IMessage.Kind)
  1947. */
  1948. @Override
  1949. public void ignore(Kind kind) {
  1950. }
  1951. }
  1952. }