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.

LangUtil.java 44KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269
  1. /* *******************************************************************
  2. * Copyright (c) 1999-2000 Xerox Corporation.
  3. * All rights reserved.
  4. * This program and the accompanying materials are made available
  5. * under the terms of the Eclipse Public License v1.0
  6. * which accompanies this distribution and is available at
  7. * http://www.eclipse.org/legal/epl-v10.html
  8. *
  9. * Contributors:
  10. * Xerox/PARC initial implementation
  11. * ******************************************************************/
  12. package org.aspectj.testing.util;
  13. import java.io.File;
  14. import java.io.FileFilter;
  15. import java.io.IOException;
  16. import java.io.PrintWriter;
  17. import java.io.StringWriter;
  18. import java.lang.reflect.Field;
  19. import java.lang.reflect.InvocationTargetException;
  20. import java.lang.reflect.Modifier;
  21. import java.security.AccessController;
  22. import java.security.PrivilegedActionException;
  23. import java.security.PrivilegedExceptionAction;
  24. import java.util.ArrayList;
  25. import java.util.BitSet;
  26. import java.util.Collections;
  27. import java.util.Comparator;
  28. import java.util.Iterator;
  29. import java.util.List;
  30. import java.util.Properties;
  31. import java.util.StringTokenizer;
  32. import org.aspectj.bridge.AbortException;
  33. import org.aspectj.bridge.IMessage;
  34. /**
  35. * misc lang utilities
  36. */
  37. public class LangUtil {
  38. /** Delimiter used by split(String) (and ArrayList.toString()?) */
  39. public static final String SPLIT_DELIM = ", ";
  40. /** prefix used by split(String) (and ArrayList.toString()?) */
  41. public static final String SPLIT_START = "[";
  42. /** suffix used by split(String) (and ArrayList.toString()?) */
  43. public static final String SPLIT_END = "]";
  44. /** system-dependent classpath separator */
  45. public static final String CLASSPATH_SEP;
  46. private static final String[] NONE = new String[0];
  47. /** bad: hard-wired unix, windows, mac path separators */
  48. private static final char[] SEPS = new char[] { '/', '\\', ':' };
  49. static {
  50. // XXX this has to be the wrong way to get system-dependent classpath separator
  51. String ps = ";";
  52. try {
  53. ps = System.getProperty("path.separator");
  54. if (null == ps) {
  55. ps = ";";
  56. String cp = System.getProperty("java.class.path");
  57. if (null != cp) {
  58. if (cp.contains(";")) {
  59. ps = ";";
  60. } else if (cp.contains(":")) {
  61. ps = ":";
  62. }
  63. // else warn?
  64. }
  65. }
  66. } catch (Throwable t) { // ignore
  67. } finally {
  68. CLASSPATH_SEP = ps;
  69. }
  70. }
  71. /**
  72. * @return input if any are empty or no target in input,
  73. * or input with escape prefixing all original target
  74. */
  75. public static String escape(String input, String target, String escape) {
  76. if (isEmpty(input) || isEmpty(target) || isEmpty(escape)) {
  77. return input;
  78. }
  79. StringBuffer sink = new StringBuffer();
  80. escape(input, target, escape, sink);
  81. return sink.toString();
  82. }
  83. /**
  84. * Append escaped input to sink.
  85. * Cheap form of arbitrary escaping does not escape the escape String
  86. * itself, but unflatten treats it as significant only before the target.
  87. * (so this fails with input that ends with target).
  88. */
  89. public static void escape(String input, String target, String escape, StringBuffer sink) {
  90. if ((null == sink) || isEmpty(input) || isEmpty(target) || isEmpty(escape)) {
  91. return;
  92. } else if (!input.contains(target)) { // avoid StringTokenizer construction
  93. sink.append(input);
  94. return;
  95. }
  96. throw new Error("unimplemented");
  97. }
  98. /** flatten list per spec to sink */
  99. public static void flatten(List list, FlattenSpec spec, StringBuffer sink) {
  100. throwIaxIfNull(spec, "spec");
  101. final FlattenSpec s = spec;
  102. flatten(list, s.prefix, s.nullFlattened, s.escape, s.delim, s.suffix, sink);
  103. }
  104. /**
  105. * Flatten a List to String by first converting to String[]
  106. * (using toString() if the elements are not already String)
  107. * and calling flatten(String[]...).
  108. */
  109. public static void flatten(
  110. List list,
  111. String prefix,
  112. String nullFlattened,
  113. String escape,
  114. String delim,
  115. String suffix,
  116. StringBuffer sink) {
  117. throwIaxIfNull(list, "list");
  118. Object[] ra = list.toArray();
  119. String[] result;
  120. if (String.class == ra.getClass().getComponentType()) {
  121. result = (String[]) ra;
  122. } else {
  123. result = new String[ra.length];
  124. for (int i = 0; i < result.length; i++) {
  125. if (null != ra[i]) {
  126. result[i] = ra[i].toString();
  127. }
  128. }
  129. }
  130. flatten(result, prefix, nullFlattened, escape, delim, suffix, sink);
  131. }
  132. /** flatten String[] per spec to sink */
  133. public static void flatten(String[] input, FlattenSpec spec, StringBuffer sink) {
  134. throwIaxIfNull(spec, "spec");
  135. final FlattenSpec s = spec;
  136. flatten(input, s.prefix, s.nullFlattened, s.escape, s.delim,s.suffix, sink);
  137. }
  138. /**
  139. * Flatten a String[] to String by writing strings to sink,
  140. * prefixing with leader (if not null),
  141. * using nullRendering for null entries (skipped if null),
  142. * escaping any delim in entry by prefixing with escape (if not null),
  143. * separating entries with delim (if not null),
  144. * and suffixing with trailer (if not null).
  145. * Note that nullFlattened is not processed for internal delim,
  146. * and strings is not copied before processing.
  147. * @param strings the String[] input - not null
  148. * @param prefix the output starts with this if not null
  149. * @param nullFlattened the output of a null entry - entry is skipped (no delim) if null
  150. * @param escape any delim in an item will be prefixed by escape if not null
  151. * @param delim two items in the output will be separated by delim if not null
  152. * @param suffix the output ends with this if not null
  153. * @param sink the StringBuffer to use for output
  154. * @return null if sink is not null (results added to sink) or rendering otherwise
  155. */
  156. public static void flatten(
  157. String[] strings,
  158. String prefix,
  159. String nullFlattened,
  160. String escape,
  161. String delim,
  162. String suffix,
  163. StringBuffer sink) {
  164. throwIaxIfNull(strings, "strings");
  165. if (null == sink) {
  166. return;
  167. }
  168. final boolean haveDelim = (!isEmpty(delim));
  169. final boolean haveNullFlattened = (null != nullFlattened);
  170. final boolean escaping = (haveDelim && (null != escape));
  171. final int numStrings = (null == strings ? 0 : strings.length);
  172. if (null != prefix) {
  173. sink.append(prefix);
  174. }
  175. for (int i = 0; i < numStrings; i++) {
  176. String s = strings[i];
  177. if (null == s) {
  178. if (!haveNullFlattened) {
  179. continue;
  180. }
  181. if (haveDelim && (i > 0)) {
  182. sink.append(delim);
  183. }
  184. sink.append(nullFlattened);
  185. } else {
  186. if (haveDelim && (i > 0)) {
  187. sink.append(delim);
  188. }
  189. if (escaping) {
  190. escape(s, delim, escape, sink);
  191. } else {
  192. sink.append(s);
  193. }
  194. }
  195. }
  196. if (null != suffix) {
  197. sink.append(suffix);
  198. }
  199. }
  200. /**
  201. * Get indexes of any invalid entries in array.
  202. * @param ra the Object[] entries to check
  203. * (if null, this returns new int[] { -1 })
  204. * @param superType the Class, if any, to verify that
  205. * any entries are assignable.
  206. * @return null if all entries are non-null, assignable to superType
  207. * or comma-delimited error String, with components
  208. * <code>"[#] {null || not {superType}"</code>,
  209. * e.g., "[3] null, [5] not String"
  210. */
  211. public static String invalidComponents(Object[] ra, Class superType) {
  212. if (null == ra) {
  213. return "null input array";
  214. } else if (0 == ra.length) {
  215. return null;
  216. }
  217. StringBuffer result = new StringBuffer();
  218. final String cname = LangUtil.unqualifiedClassName(superType);
  219. // int index = 0;
  220. for (int i = 0; i < ra.length; i++) {
  221. if (null == ra[i]) {
  222. result.append(", [" + i + "] null");
  223. } else if ((null != superType)
  224. && !superType.isAssignableFrom(ra[i].getClass())) {
  225. result.append(", [" + i + "] not " + cname);
  226. }
  227. }
  228. if (0 == result.length()) {
  229. return null;
  230. } else {
  231. return result.toString().substring(2);
  232. }
  233. }
  234. /** @return ((null == ra) || (0 == ra.length)) */
  235. public static boolean isEmpty(Object[] ra) {
  236. return ((null == ra) || (0 == ra.length));
  237. }
  238. /** @return ((null == s) || (0 == s.length())); */
  239. public static boolean isEmpty(String s) {
  240. return ((null == s) || (0 == s.length()));
  241. }
  242. /**
  243. * Throw IllegalArgumentException if any component in input array
  244. * is null or (if superType is not null) not assignable to superType.
  245. * The exception message takes the form
  246. * <code>{name} invalid entries: {invalidEntriesResult}</code>
  247. * @throws IllegalArgumentException if any components bad
  248. * @see #invalidComponents(Object[], Class)
  249. */
  250. public static final void throwIaxIfComponentsBad(
  251. final Object[] input,
  252. final String name,
  253. final Class superType) {
  254. String errs = invalidComponents(input, superType);
  255. if (null != errs) {
  256. String err = name + " invalid entries: " + errs;
  257. throw new IllegalArgumentException(err);
  258. }
  259. }
  260. /**
  261. * Shorthand for "if false, throw IllegalArgumentException"
  262. * @throws IllegalArgumentException "{message}" if test is false
  263. */
  264. public static final void throwIaxIfFalse(final boolean test, final String message) {
  265. if (!test) {
  266. throw new IllegalArgumentException(message);
  267. }
  268. }
  269. /**
  270. * Shorthand for "if null, throw IllegalArgumentException"
  271. * @throws IllegalArgumentException "null {name}" if o is null
  272. */
  273. public static final void throwIaxIfNull(final Object o, final String name) {
  274. if (null == o) {
  275. String message = "null " + (null == name ? "input" : name);
  276. throw new IllegalArgumentException(message);
  277. }
  278. }
  279. public static ArrayList unflatten(String input, FlattenSpec spec) {
  280. throwIaxIfNull(spec, "spec");
  281. final FlattenSpec s = spec;
  282. return unflatten(input,s.prefix, s.nullFlattened, s.escape, s.delim, s.suffix, s.emptyUnflattened);
  283. }
  284. /**
  285. * Unflatten a String to String[] by separating elements at delim,
  286. * handling prefixes, suffixes, escapes, etc.
  287. * Any prefix or suffix is stripped from the input
  288. * (or, if not found, an IllegalArgumentException is thrown).
  289. * If delim is null or empty or input contains no delim,
  290. * then return new String[] {stripped input}.
  291. *
  292. * XXX fix comments
  293. * prefixing with leader (if not null),
  294. * using nullRendering for null entries (skipped if null),
  295. * escaping any delim in entry by prefixing with escape (if not null),
  296. * separating entries with delim (if not null),
  297. * and suffixing with trailer (if not null).
  298. * Note that nullRendering is not processed for internal delim,
  299. * and strings is not copied before processing.
  300. * @param strings the String[] input - not null
  301. * @param prefix the output starts with this if not null
  302. * @param nullRendering the output of a null entry - entry is skipped (no delim) if null
  303. * @param escape any delim in an item will be prefixed by escape if not null
  304. * @param delim two items in the output will be separated by delim if not null
  305. * @param suffix the output ends with this if not null
  306. * @param sink the StringBuffer to use for output
  307. * @return null if sink is not null (results added to sink) or rendering otherwise
  308. * @throws IllegalArgumentException if input is null
  309. * or if any prefix does not start the input
  310. * or if any suffix does not end the input
  311. */
  312. public static ArrayList unflatten(
  313. String input,
  314. String prefix,
  315. String nullFlattened,
  316. String escape,
  317. String delim,
  318. String suffix,
  319. String emptyUnflattened) {
  320. throwIaxIfNull(input, "input");
  321. final boolean haveDelim = (!isEmpty(delim));
  322. // final boolean haveNullFlattened = (null != nullFlattened);
  323. // final boolean escaping = (haveDelim && (null != escape));
  324. if (!isEmpty(prefix)) {
  325. if (input.startsWith(prefix)) {
  326. input = input.substring(prefix.length());
  327. } else {
  328. String s = "expecting \"" + prefix + "\" at start of " + input + "\"";
  329. throw new IllegalArgumentException(s);
  330. }
  331. }
  332. if (!isEmpty(suffix)) {
  333. if (input.endsWith(suffix)) {
  334. input = input.substring(0, input.length() - suffix.length());
  335. } else {
  336. String s = "expecting \"" + suffix + "\" at end of " + input + "\"";
  337. throw new IllegalArgumentException(s);
  338. }
  339. }
  340. final ArrayList result = new ArrayList();
  341. if (isEmpty(input)) {
  342. return result;
  343. }
  344. if ((!haveDelim) || (!input.contains(delim))) {
  345. result.add(input);
  346. return result;
  347. }
  348. StringTokenizer st = new StringTokenizer(input, delim, true);
  349. // StringBuffer cur = new StringBuffer();
  350. // boolean lastEndedWithEscape = false;
  351. // boolean lastWasDelim = false;
  352. while (st.hasMoreTokens()) {
  353. String token = st.nextToken();
  354. System.out.println("reading " + token);
  355. if (delim.equals(token)) {
  356. } else {
  357. result.add(token);
  358. }
  359. }
  360. return result;
  361. }
  362. /** combine two string arrays, removing null and duplicates
  363. * @return concatenation of both arrays, less null in either or dups in two
  364. * @see Util#combine(Object[], Object[])
  365. */
  366. public static String[] combine(String[] one, String[] two) {
  367. ArrayList twoList = new ArrayList();
  368. twoList.addAll(org.aspectj.util.LangUtil.arrayAsList(two));
  369. ArrayList result = new ArrayList();
  370. if (null != one) {
  371. for (String s : one) {
  372. if (null != s) {
  373. twoList.remove(s);
  374. result.add(s);
  375. }
  376. }
  377. }
  378. for (Object o : twoList) {
  379. String element = (String) o;
  380. if (null != element) {
  381. result.add(element);
  382. }
  383. }
  384. return (String[]) result.toArray(NONE);
  385. }
  386. public static Properties combine(Properties dest, Properties add, boolean respectExisting) { // XXX
  387. if (null == add) return dest;
  388. if (null == dest) return add;
  389. for (Object o : add.keySet()) {
  390. String key = (String) o;
  391. if (null == key) {
  392. continue;
  393. }
  394. String value = add.getProperty(key);
  395. if (null == value) {
  396. continue;
  397. }
  398. if (!respectExisting || (null == dest.getProperty(key))) {
  399. dest.setProperty(key, value);
  400. }
  401. }
  402. return dest;
  403. }
  404. public static List arrayAsList(Object[] ra) {
  405. return org.aspectj.util.LangUtil.arrayAsList(ra);
  406. }
  407. /**
  408. * return the fully-qualified class names
  409. * inferred from the file names in dir
  410. * assuming dir is the root of the source tree
  411. * and class files end with ".class".
  412. * @throws Error if dir is not properly named as prefix
  413. * of class files found in dir.
  414. */
  415. public static String[] classesIn(File dir) {
  416. boolean alwaysTrue = true;
  417. FileFilter filter = ValidFileFilter.CLASS_FILE;
  418. CollectorFileFilter collector = new CollectorFileFilter(filter, alwaysTrue);
  419. FileUtil.descendFileTree(dir, collector);
  420. List list = collector.getFiles();
  421. String[] result = new String[list.size()];
  422. Iterator it = list.iterator();
  423. String dirPrefix = dir.getPath();
  424. for (int i = 0; i < result.length; i++) {
  425. if (!it.hasNext()) {
  426. throw new Error("unexpected end of list at " + i);
  427. }
  428. result[i] = fileToClassname((File) it.next(), dirPrefix);
  429. }
  430. return result;
  431. }
  432. /**
  433. * Convert String[] to String by using conventions for
  434. * split. Will ignore any entries containing SPLIT_DELIM
  435. * (and write as such to errs if not null).
  436. * @param input the String[] to convert
  437. * @param errs the StringBuffer for error messages (if any)
  438. */
  439. public static String unsplit(String[] input, StringBuffer errs) {
  440. StringBuffer sb = new StringBuffer();
  441. sb.append(SPLIT_START);
  442. for (int i = 0; i < input.length; i++) {
  443. if (input[i].contains(SPLIT_DELIM)) {
  444. if (null != errs) {
  445. errs.append("\nLangUtil.unsplit(..) - item " + i + ": \"" + input[i]
  446. + " contains \"" + SPLIT_DELIM + "\"");
  447. }
  448. } else {
  449. sb.append(input[i]);
  450. if (1+i < input.length) {
  451. sb.append(SPLIT_DELIM);
  452. }
  453. }
  454. }
  455. sb.append(SPLIT_END);
  456. return sb.toString();
  457. }
  458. /**
  459. * Split input into substrings on the assumption that it is
  460. * either only one string or it was generated using List.toString(),
  461. * with tokens
  462. * <pre>SPLIT_START {string} { SPLIT_DELIM {string}} SPLIT_END<pre>
  463. * (e.g., <code>"[one, two, three]"</code>).
  464. */
  465. public static String[] split(String s) {
  466. if (null == s) {
  467. return null;
  468. }
  469. if ((!s.startsWith(SPLIT_START)) || (!s.endsWith(SPLIT_END))) {
  470. return new String[] { s };
  471. }
  472. s = s.substring(SPLIT_START.length(),s.length()-SPLIT_END.length());
  473. final int LEN = s.length();
  474. int start = 0;
  475. final ArrayList result = new ArrayList();
  476. final String DELIM = ", ";
  477. int loc = s.indexOf(SPLIT_DELIM, start);
  478. while ((start < LEN) && (-1 != loc)) {
  479. result.add(s.substring(start, loc));
  480. start = DELIM.length() + loc;
  481. loc = s.indexOf(SPLIT_DELIM, start);
  482. }
  483. result.add(s.substring(start));
  484. return (String[]) result.toArray(new String[0]);
  485. }
  486. public static String[] strip(String[] src, String[] toStrip) {
  487. if (null == toStrip) {
  488. return strip(src, NONE);
  489. } else if (null == src) {
  490. return strip(NONE, toStrip);
  491. }
  492. List slist = org.aspectj.util.LangUtil.arrayAsList(src);
  493. List tlist = org.aspectj.util.LangUtil.arrayAsList(toStrip);
  494. slist.removeAll(tlist);
  495. return (String[]) slist.toArray(NONE);
  496. }
  497. /**
  498. * Load all classes specified by args, logging success to out
  499. * and fail to err.
  500. */
  501. public static void loadClasses(String[] args, StringBuffer out,
  502. StringBuffer err) {
  503. if (null != args) {
  504. for (String arg : args) {
  505. try {
  506. Class c = Class.forName(arg);
  507. if (null != out) {
  508. out.append("\n");
  509. out.append(arg);
  510. out.append(": ");
  511. out.append(c.getName());
  512. }
  513. } catch (Throwable t) {
  514. if (null != err) {
  515. err.append("\n");
  516. FileUtil.render(t, err);
  517. }
  518. }
  519. }
  520. }
  521. }
  522. private static String fileToClassname(File f, String prefix) {
  523. // this can safely assume file exists, starts at base, ends with .class
  524. // this WILL FAIL if full path with drive letter on windows
  525. String path = f.getPath();
  526. if (!path.startsWith(prefix)) {
  527. String err = "!\"" + path + "\".startsWith(\"" + prefix + "\")";
  528. throw new IllegalArgumentException(err);
  529. }
  530. int length = path.length() - ".class".length();
  531. path = path.substring(prefix.length()+1, length);
  532. for (char sep : SEPS) {
  533. path = path.replace(sep, '.');
  534. }
  535. return path;
  536. }
  537. public static void main (String[] args) { // todo remove as testing
  538. StringBuffer err = new StringBuffer();
  539. StringBuffer out = new StringBuffer();
  540. for (String arg : args) {
  541. String[] names = classesIn(new File(arg));
  542. System.err.println(arg + " -> " + render(names));
  543. loadClasses(names, out, err);
  544. }
  545. if (0 < err.length()) {
  546. System.err.println(err.toString());
  547. }
  548. if (0 < out.length()) {
  549. System.out.println(out.toString());
  550. }
  551. }
  552. public static String render (String[] args) { // todo move as testing
  553. if ((null == args) || (1 > args.length)) {
  554. return "[]";
  555. }
  556. boolean longFormat = (args.length < 10);
  557. String sep = (longFormat ? ", " : "\n\t");
  558. StringBuffer sb = new StringBuffer();
  559. if (!longFormat) sb.append("[");
  560. for (int i = 0; i < args.length; i++) {
  561. if (0 < i) sb.append(sep);
  562. sb.append(args[i]);
  563. }
  564. sb.append(longFormat ? "\n" : "]");
  565. return sb.toString();
  566. }
  567. /**
  568. * @param thrown the Throwable to render
  569. */
  570. public static String debugStr(Throwable thrown) {
  571. if (null == thrown) {
  572. return "((Throwable) null)";
  573. } else if (thrown instanceof InvocationTargetException) {
  574. return debugStr(((InvocationTargetException)thrown).getTargetException());
  575. } else if (thrown instanceof AbortException) {
  576. IMessage m = ((AbortException) thrown).getIMessage();
  577. if (null != m) {
  578. return "" + m;
  579. }
  580. }
  581. StringWriter buf = new StringWriter();
  582. PrintWriter writer = new PrintWriter(buf);
  583. writer.println(thrown.getMessage());
  584. thrown.printStackTrace(writer);
  585. try { buf.close(); }
  586. catch (IOException ioe) {}
  587. return buf.toString();
  588. }
  589. /**
  590. * <code>debugStr(o, false);</code>
  591. * @param source the Object to render
  592. */
  593. public static String debugStr(Object o) {
  594. return debugStr(o, false);
  595. }
  596. /**
  597. * Render standard debug string for an object in normal, default form.
  598. * @param source the Object to render
  599. * @param recurse if true, then recurse on all non-primitives unless rendered
  600. */
  601. public static String debugStr(Object o, boolean recurse) {
  602. if (null == o) {
  603. return "null";
  604. } else if (recurse) {
  605. ArrayList rendering = new ArrayList();
  606. rendering.add(o);
  607. return debugStr(o, rendering);
  608. } else {
  609. Class c = o.getClass();
  610. Field[] fields = c.getDeclaredFields();
  611. Object[] values = new Object[fields.length];
  612. String[] names = new String[fields.length];
  613. for (int i = 0; i < fields.length; i++) {
  614. Field field = fields[i];
  615. names[i] = field.getName();
  616. try {
  617. values[i] = field.get(o);
  618. if (field.getType().isArray()) {
  619. List list = org.aspectj.util.LangUtil.arrayAsList((Object[]) values[i]);
  620. values[i] = list.toString();
  621. }
  622. } catch (IllegalAccessException e) {
  623. values[i] = "<IllegalAccessException>";
  624. }
  625. }
  626. return debugStr(c, names, values);
  627. }
  628. }
  629. /**
  630. * recursive variant avoids cycles.
  631. * o added to rendering before call.
  632. */
  633. private static String debugStr(Object o, ArrayList rendering) {
  634. if (null == o) {
  635. return "null";
  636. } else if (!rendering.contains(o)) {
  637. throw new Error("o not in rendering");
  638. }
  639. Class c = o.getClass();
  640. if (c.isArray()) {
  641. Object[] ra = (Object[]) o;
  642. StringBuffer sb = new StringBuffer();
  643. sb.append("[");
  644. for (int i = 0; i < ra.length; i++) {
  645. if (i > 0) {
  646. sb.append(", ");
  647. }
  648. rendering.add(ra[i]);
  649. sb.append(debugStr(ra[i], rendering));
  650. }
  651. sb.append("]");
  652. return sb.toString();
  653. }
  654. Field[] fields = nonStaticFields(c.getFields());
  655. Object[] values = new Object[fields.length];
  656. String[] names = new String[fields.length];
  657. for (int i = 0; i < fields.length; i++) {
  658. Field field = fields[i];
  659. names[i] = field.getName();
  660. // collapse to String
  661. Object value = privilegedGetField(field,o);
  662. if (null == value) {
  663. values[i] = "null";
  664. } else if (rendering.contains(value)) {
  665. values[i] = "<recursion>";
  666. } else {
  667. rendering.add(value);
  668. values[i] = debugStr(value, rendering);
  669. }
  670. }
  671. return debugStr(c, names, values);
  672. }
  673. /** incomplete - need protection domain */
  674. private static Object privilegedGetField(final Field field, final Object o) {
  675. try {
  676. return AccessController.doPrivileged(new PrivilegedExceptionAction() {
  677. public Object run() {
  678. try {
  679. return field.get(o);
  680. } catch(IllegalAccessException e) {
  681. return "<IllegalAccessException>";
  682. }
  683. }
  684. });
  685. } catch (PrivilegedActionException e) {
  686. return "<IllegalAccessException>";
  687. }
  688. }
  689. private static Field[] nonStaticFields(Field[] fields) {
  690. if (null == fields) {
  691. return new Field[0];
  692. }
  693. int to = 0;
  694. int from = 0;
  695. while (from < fields.length) {
  696. if (!Modifier.isStatic(fields[from].getModifiers())) {
  697. if (to != from) {
  698. fields[to] = fields[from];
  699. }
  700. to++;
  701. }
  702. from++;
  703. }
  704. if (to < from) {
  705. Field[] result = new Field[to];
  706. if (to > 0) {
  707. System.arraycopy(fields, 0, result, 0, to);
  708. }
  709. fields = result;
  710. }
  711. return fields;
  712. }
  713. /** <code> debugStr(source, names, items, null, null, null, null)<code> */
  714. public static String debugStr(Class source, String[] names, Object[] items) {
  715. return debugStr(source, null, names, null, items, null, null);
  716. }
  717. /**
  718. * Render standard debug string for an object.
  719. * This is the normal form and an example with the default values:<pre>
  720. * {className}{prefix}{{name}{infix}{value}{delimiter}}..{suffix}
  721. * Structure[head=root, tail=leaf]</pre>
  722. * Passing null for the formatting entries provokes the default values,
  723. * so to print nothing, you should pass "". Default values:<pre>
  724. * prefix: "[" SPLIT_START
  725. * infix: "="
  726. * delimiter: ", " SPLIT_DELIM
  727. * suffix: "]" SPLIT_END
  728. * @param source the Class prefix to render unqualified - omitted if null
  729. * @param names the String[] (field) names of the items - omitted if null
  730. * @param items the Object[] (field) values
  731. * @param prefix the String to separate classname and start of name/values
  732. * @param delimiter the String to separate name/value instances
  733. * @param infix the String to separate name and value
  734. * used only if both name and value exist
  735. * @param suffix the String to delimit the end of the name/value instances
  736. * used only if classname exists
  737. */
  738. public static String debugStr(Class source, String prefix, String[] names,
  739. String infix, Object[] items, String delimiter, String suffix) {
  740. if (null == delimiter) {
  741. delimiter = SPLIT_DELIM;
  742. }
  743. if (null == prefix) {
  744. prefix = SPLIT_START;
  745. }
  746. if (null == infix) {
  747. infix = "=";
  748. }
  749. if (null == suffix) {
  750. suffix = SPLIT_END;
  751. }
  752. StringBuffer sb = new StringBuffer();
  753. if (null != source) {
  754. sb.append(org.aspectj.util.LangUtil.unqualifiedClassName(source));
  755. }
  756. sb.append(prefix);
  757. if (null == names) {
  758. names = NONE;
  759. }
  760. if (null == items) {
  761. items = NONE;
  762. }
  763. final int MAX
  764. = (names.length > items.length ? names.length : items.length);
  765. for (int i = 0; i < MAX; i++) {
  766. if (i > 0) {
  767. sb.append(delimiter);
  768. }
  769. if (i < names.length) {
  770. sb.append(names[i]);
  771. }
  772. if (i < items.length) {
  773. if (i < names.length) {
  774. sb.append(infix);
  775. }
  776. sb.append(items[i] + "");
  777. }
  778. }
  779. sb.append(suffix);
  780. return sb.toString();
  781. }
  782. /**
  783. * @return a String with the unqualified class name of the object (or "null")
  784. */
  785. public static String unqualifiedClassName(Object o) {
  786. return unqualifiedClassName(null == o ? null : o.getClass());
  787. }
  788. /**
  789. * @return a String with the unqualified class name of the class (or "null")
  790. */
  791. public static String unqualifiedClassName(Class c) {
  792. if (null == c) {
  793. return "null";
  794. }
  795. String name = c.getName();
  796. int loc = name.lastIndexOf(".");
  797. if (-1 != loc)
  798. name = name.substring(1 + loc);
  799. return name;
  800. }
  801. /**
  802. * Calculate exact diffs and report missing and extra items.
  803. * This assumes the input List are not modified concurrently.
  804. * @param expectedListIn the List of expected results - treated as empty if null
  805. * @param actualListIn the List of actual results - treated as empty if null
  806. * @param extraListOut the List for any actual results not expected - ignored if null
  807. * @param missingListOut the List for any expected results not found - ignored if null
  808. * */
  809. public static void makeDiffs(
  810. List expectedListIn,
  811. List actualListIn,
  812. List missingListOut,
  813. List extraListOut) {
  814. if ((null == missingListOut) && (null == extraListOut)) {
  815. return;
  816. }
  817. if (null == expectedListIn) {
  818. expectedListIn = Collections.EMPTY_LIST;
  819. }
  820. if (null == actualListIn) {
  821. actualListIn = Collections.EMPTY_LIST;
  822. }
  823. if ((0 == actualListIn.size()) && (0 == expectedListIn.size()) ) {
  824. return;
  825. }
  826. BitSet actualExpected = new BitSet();
  827. for (Object expect : expectedListIn) {
  828. int loc = actualListIn.indexOf(expect);
  829. if (-1 == loc) {
  830. if (null != missingListOut) {
  831. missingListOut.add(expect);
  832. }
  833. } else {
  834. actualExpected.set(loc);
  835. }
  836. }
  837. if (null != extraListOut) {
  838. for (int i = 0; i < actualListIn.size(); i++) {
  839. if (!actualExpected.get(i)) {
  840. extraListOut.add(actualListIn.get(i));
  841. }
  842. }
  843. }
  844. }
  845. // XXX unit test for makeSoftDiffs
  846. /**
  847. * Calculate potentially "soft" diffs using
  848. * Comparator.compare(expected, actual).
  849. * This shallow-copies and sorts the input Lists.
  850. * @param expectedListIn the List of expected results - treated as empty if null
  851. * @param actualListIn the List of actual results - treated as empty if null
  852. * @param extraListOut the List for any actual results not expected - ignored if null
  853. * @param missingListOut the List for any expected results not found - ignored if null
  854. * @param comparator the Comparator for comparisons - not null
  855. * @throws IllegalArgumentException if comp is null
  856. */
  857. public static void makeSoftDiffs( // XXX no intersect or union on collections???
  858. List expectedListIn,
  859. List actualListIn,
  860. List missingListOut,
  861. List extraListOut,
  862. Comparator comparator) {
  863. if ((null == missingListOut) && (null == extraListOut)) {
  864. return;
  865. }
  866. if (null == comparator) {
  867. throw new IllegalArgumentException("null comparator");
  868. }
  869. if (null == expectedListIn) {
  870. expectedListIn = Collections.EMPTY_LIST;
  871. }
  872. if (null == actualListIn) {
  873. actualListIn = Collections.EMPTY_LIST;
  874. }
  875. if ((0 == actualListIn.size()) && (0 == expectedListIn.size()) ) {
  876. return;
  877. }
  878. ArrayList expected = new ArrayList();
  879. expected.addAll(expectedListIn);
  880. Collections.sort(expected, comparator);
  881. ArrayList actual = new ArrayList();
  882. actual.addAll(actualListIn);
  883. Collections.sort(actual, comparator);
  884. Iterator actualIter = actual.iterator();
  885. Object act = null;
  886. if (missingListOut != null) {
  887. missingListOut.addAll(expectedListIn);
  888. }
  889. if (extraListOut != null) {
  890. extraListOut.addAll(actualListIn);
  891. }
  892. // AMC: less efficient, but simplified implementation. Needed since messages can
  893. // now match on text content too, and the old algorithm did not cope with two expected
  894. // messages on the same line, but with different text content.
  895. while (actualIter.hasNext()) {
  896. act = actualIter.next();
  897. for (Object exp : expected) {
  898. // if actual matches expected remove actual from extraListOut, and
  899. // remove expected from missingListOut
  900. int diff = comparator.compare(exp, act);
  901. if (diff == 0) {
  902. extraListOut.remove(act);
  903. missingListOut.remove(exp);
  904. } else if (diff > 0) {
  905. // since list is sorted, there can be no more matches...
  906. break;
  907. }
  908. }
  909. }
  910. // while (((null != act) || actualIter.hasNext())
  911. // && ((null != exp) || expectedIter.hasNext())) {
  912. // if (null == act) {
  913. // act = actualIter.next();
  914. // }
  915. // if (null == exp) {
  916. // exp = expectedIter.next();
  917. // }
  918. // int diff = comparator.compare(exp, act);
  919. // if (0 > diff) { // exp < act
  920. // if (null != missingListOut) {
  921. // missingListOut.add(exp);
  922. // exp = null;
  923. // }
  924. // } else if (0 < diff) { // exp > act
  925. // if (null != extraListOut) {
  926. // extraListOut.add(act);
  927. // act = null;
  928. // }
  929. // } else { // got match of actual to expected
  930. // // absorb all actual matching expected (duplicates)
  931. // while ((0 == diff) && actualIter.hasNext()) {
  932. // act = actualIter.next();
  933. // diff = comparator.compare(exp, act);
  934. // }
  935. // if (0 == diff) {
  936. // act = null;
  937. // }
  938. // exp = null;
  939. // }
  940. // }
  941. // if (null != missingListOut) {
  942. // if (null != exp) {
  943. // missingListOut.add(exp);
  944. // }
  945. // while (expectedIter.hasNext()) {
  946. // missingListOut.add(expectedIter.next());
  947. // }
  948. // }
  949. // if (null != extraListOut) {
  950. // if (null != act) {
  951. // extraListOut.add(act);
  952. // }
  953. // while (actualIter.hasNext()) {
  954. // extraListOut.add(actualIter.next());
  955. // }
  956. // }
  957. }
  958. public static class FlattenSpec {
  959. /**
  960. * This tells unflatten(..) to throw IllegalArgumentException
  961. * if it finds two contiguous delimiters.
  962. */
  963. public static final String UNFLATTEN_EMPTY_ERROR
  964. = "empty items not permitted when unflattening";
  965. /**
  966. * This tells unflatten(..) to skip empty items when unflattening
  967. * (since null means "use null")
  968. */
  969. public static final String UNFLATTEN_EMPTY_AS_NULL
  970. = "unflatten empty items as null";
  971. /**
  972. * This tells unflatten(..) to skip empty items when unflattening
  973. * (since null means "use null")
  974. */
  975. public static final String SKIP_EMPTY_IN_UNFLATTEN
  976. = "skip empty items when unflattening";
  977. /**
  978. * For Ant-style attributes: "item,item" (with escaped commas).
  979. * There is no way when unflattening to distinguish
  980. * values which were empty from those which were null,
  981. * so all are unflattened as empty.
  982. */
  983. public static final FlattenSpec COMMA
  984. = new FlattenSpec(null, "", "\\", ",", null, "") {
  985. public String toString() { return "FlattenSpec.COMMA"; }
  986. };
  987. /** this attempts to mimic ((List)l).toString() */
  988. public static final FlattenSpec LIST
  989. = new FlattenSpec("[", "", null, ", ", "]", UNFLATTEN_EMPTY_ERROR) {
  990. public String toString() { return "FlattenSpec.LIST"; }
  991. };
  992. /** how toString renders null values */
  993. public static final String NULL = "<null>";
  994. private static String r(String s) {
  995. return (null == s ? NULL : s);
  996. }
  997. public final String prefix;
  998. public final String nullFlattened;
  999. public final String escape;
  1000. public final String delim;
  1001. public final String suffix;
  1002. public final String emptyUnflattened;
  1003. private transient String toString;
  1004. public FlattenSpec(
  1005. String prefix,
  1006. String nullRendering,
  1007. String escape,
  1008. String delim,
  1009. String suffix,
  1010. String emptyUnflattened) {
  1011. this.prefix = prefix;
  1012. this.nullFlattened = nullRendering;
  1013. this.escape = escape;
  1014. this.delim = delim;
  1015. this.suffix = suffix;
  1016. this.emptyUnflattened = emptyUnflattened;
  1017. throwIaxIfNull(emptyUnflattened, "use UNFLATTEN_EMPTY_AS_NULL");
  1018. }
  1019. public String toString() {
  1020. if (null == toString) {
  1021. toString = "FlattenSpec("
  1022. + "prefix=" + r(prefix)
  1023. + ", nullRendering=" + r(nullFlattened)
  1024. + ", escape=" + r(escape)
  1025. + ", delim=" + r(delim)
  1026. + ", suffix=" + r(suffix)
  1027. + ", emptyUnflattened=" + r(emptyUnflattened)
  1028. + ")";
  1029. }
  1030. return toString;
  1031. }
  1032. }
  1033. } // class LangUtil
  1034. // --------- java runs using Ant
  1035. // /**
  1036. // * Run a Java command separately.
  1037. // * @param className the fully-qualified String name of the class
  1038. // * with the main method to run
  1039. // * @param classpathFiles the File to put on the classpath
  1040. // * @param args to the main method of the class
  1041. // * @param outSink the PrintStream for the output stream - may be null
  1042. // */
  1043. // public static void oldexecuteJava(
  1044. // String className,
  1045. // File[] classpathFiles,
  1046. // String[] args,
  1047. // PrintStream outSink) {
  1048. // Project project = new Project();
  1049. // project.setName("LangUtil.executeJava(" + className + ")");
  1050. // Path classpath = new Path(project, classpathFiles[0].getAbsolutePath());
  1051. // for (int i = 1; i < classpathFiles.length; i++) {
  1052. // classpath.addExisting(new Path(project, classpathFiles[i].getAbsolutePath()));
  1053. // }
  1054. //
  1055. // Commandline cmds = new Commandline();
  1056. // cmds.addArguments(new String[] {className});
  1057. // cmds.addArguments(args);
  1058. //
  1059. // ExecuteJava runner = new ExecuteJava();
  1060. // runner.setClasspath(classpath);
  1061. // runner.setJavaCommand(cmds);
  1062. // if (null != outSink) {
  1063. // runner.setOutput(outSink); // XXX todo
  1064. // }
  1065. // runner.execute(project);
  1066. // }
  1067. // public static void executeJava(
  1068. // String className,
  1069. // File dir,
  1070. // File[] classpathFiles,
  1071. // String[] args,
  1072. // PrintStream outSink) {
  1073. // StringBuffer sb = new StringBuffer();
  1074. //
  1075. // sb.append("c:/apps/jdk1.3.1/bin/java.exe -classpath \"");
  1076. // for (int i = 0; i < classpathFiles.length; i++) {
  1077. // if (i < 0) {
  1078. // sb.append(";");
  1079. // }
  1080. // sb.append(classpathFiles[i].getAbsolutePath());
  1081. // }
  1082. // sb.append("\" -verbose " + className);
  1083. // for (int i = 0; i < args.length; i++) {
  1084. // sb.append(" " + args[i]);
  1085. // }
  1086. // Exec exec = new Exec();
  1087. // Project project = new Project();
  1088. // project.setProperty("ant.home", "c:/home/wes/aj/aspectj/modules/lib/ant");
  1089. // System.setProperty("ant.home", "c:/home/wes/aj/aspectj/modules/lib/ant");
  1090. // exec.setProject(new Project());
  1091. // exec.setCommand(sb.toString());
  1092. // exec.setDir(dir.getAbsolutePath());
  1093. // exec.execute();
  1094. // }
  1095. // public static void execJavaProcess(
  1096. // String className,
  1097. // File dir,
  1098. // File[] classpathFiles,
  1099. // String[] args,
  1100. // PrintStream outSink) throws Throwable {
  1101. // StringBuffer sb = new StringBuffer();
  1102. //
  1103. // sb.append("c:\\apps\\jdk1.3.1\\bin\\java.exe -classpath \"");
  1104. // for (int i = 0; i < classpathFiles.length; i++) {
  1105. // if (i > 0) {
  1106. // sb.append(";");
  1107. // }
  1108. // sb.append(classpathFiles[i].getAbsolutePath());
  1109. // }
  1110. // sb.append("\" -verbose " + className);
  1111. // for (int i = 0; i < args.length; i++) {
  1112. // sb.append(" " + args[i]);
  1113. // }
  1114. // String command = sb.toString();
  1115. // System.err.println("launching process: " + command);
  1116. // Process process = Runtime.getRuntime().exec(command);
  1117. // // huh? err/out
  1118. // InputStream errStream = null;
  1119. // InputStream outStream = null;
  1120. // Throwable toThrow = null;
  1121. // int result = -1;
  1122. // try {
  1123. // System.err.println("waiting for process: " + command);
  1124. // errStream = null; // process.getErrorStream();
  1125. // outStream = null; // process.getInputStream(); // misnamed - out
  1126. // result = process.waitFor();
  1127. // System.err.println("Done waiting for process: " + command);
  1128. // process.destroy();
  1129. // } catch (Throwable t) {
  1130. // toThrow = t;
  1131. // } finally {
  1132. // if (null != outStream) {
  1133. // FileUtil.copy(outStream, System.out, false);
  1134. // try { outStream.close(); }
  1135. // catch (IOException e) {}
  1136. // }
  1137. // if (null != errStream) {
  1138. // FileUtil.copy(errStream, System.err, false);
  1139. // try { errStream.close(); }
  1140. // catch (IOException e) {}
  1141. // }
  1142. // }
  1143. // if (null != toThrow) {
  1144. // throw toThrow;
  1145. // }
  1146. // }
  1147. // try {
  1148. // // show the command
  1149. // log(command, Project.MSG_VERBOSE);
  1150. //
  1151. // // exec command on system runtime
  1152. // Process proc = Runtime.getRuntime().exec(command);
  1153. //
  1154. // if (out != null) {
  1155. // fos = new PrintWriter(new FileWriter(out));
  1156. // log("Output redirected to " + out, Project.MSG_VERBOSE);
  1157. // }
  1158. //
  1159. // // copy input and error to the output stream
  1160. // StreamPumper inputPumper =
  1161. // new StreamPumper(proc.getInputStream(), Project.MSG_INFO);
  1162. // StreamPumper errorPumper =
  1163. // new StreamPumper(proc.getErrorStream(), Project.MSG_WARN);
  1164. //
  1165. // // starts pumping away the generated output/error
  1166. // inputPumper.start();
  1167. // errorPumper.start();
  1168. //
  1169. // // Wait for everything to finish
  1170. // proc.waitFor();
  1171. // inputPumper.join();
  1172. // errorPumper.join();
  1173. // proc.destroy();
  1174. //
  1175. // // close the output file if required
  1176. // logFlush();
  1177. //
  1178. // // check its exit value
  1179. // err = proc.exitValue();
  1180. // if (err != 0) {
  1181. // if (failOnError) {
  1182. // throw new BuildException("Exec returned: " + err, getLocation());
  1183. // } else {
  1184. // log("Result: " + err, Project.MSG_ERR);
  1185. // }
  1186. // }
  1187. // } catch (IOException ioe) {
  1188. // throw new BuildException("Error exec: " + command, ioe, getLocation());
  1189. // } catch (InterruptedException ex) {}
  1190. //