您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

AjcTask.java 61KB

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