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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247
  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 Common Public License v1.0
  6. * which accompanies this distribution and is available at
  7. * http://www.eclipse.org/legal/cpl-v10.html
  8. *
  9. * Contributors:
  10. * Xerox/PARC initial implementation
  11. * ******************************************************************/
  12. package org.aspectj.testing.util;
  13. import org.aspectj.bridge.AbortException;
  14. import org.aspectj.bridge.IMessage;
  15. import java.io.File;
  16. import java.io.FileFilter;
  17. import java.io.IOException;
  18. import java.io.PrintWriter;
  19. import java.io.StringWriter;
  20. import java.lang.reflect.Field;
  21. import java.lang.reflect.InvocationTargetException;
  22. import java.lang.reflect.Modifier;
  23. import java.security.AccessController;
  24. import java.security.PrivilegedActionException;
  25. import java.security.PrivilegedExceptionAction;
  26. import java.util.ArrayList;
  27. import java.util.BitSet;
  28. import java.util.Collections;
  29. import java.util.Comparator;
  30. import java.util.Iterator;
  31. import java.util.List;
  32. import java.util.Properties;
  33. import java.util.StringTokenizer;
  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 (-1 != cp.indexOf(";")) {
  59. ps = ";";
  60. } else if (-1 != cp.indexOf(":")) {
  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 (-1 == input.indexOf(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) || (-1 == input.indexOf(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 (int i = 0; i < one.length; i++) {
  372. if (null != one[i]) {
  373. twoList.remove(one[i]);
  374. result.add(one[i]);
  375. }
  376. }
  377. }
  378. for (Iterator iterator = twoList.iterator(); iterator.hasNext(); ) {
  379. String element = (String) iterator.next();
  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 (Iterator iterator = add.keySet().iterator(); iterator.hasNext(); ) {
  390. String key = (String) iterator.next();
  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 (-1 != input[i].indexOf(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 (int i = 0; i < args.length; i++) {
  505. try {
  506. Class c = Class.forName(args[i]);
  507. if (null != out) {
  508. out.append("\n");
  509. out.append(args[i]);
  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 (int i = 0; i < SEPS.length; i++) {
  533. path = path.replace(SEPS[i], '.');
  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 (int i = 0; i < args.length; i++) {
  541. String[] names = classesIn(new File(args[i]));
  542. System.err.println(args[i] + " -> " + 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 (int i = 0; i < expectedListIn.size(); i++) {
  828. Object expect = expectedListIn.get(i);
  829. int loc = actualListIn.indexOf(expect);
  830. if (-1 == loc) {
  831. if (null != missingListOut) {
  832. missingListOut.add(expect);
  833. }
  834. } else {
  835. actualExpected.set(loc);
  836. }
  837. }
  838. if (null != extraListOut) {
  839. for (int i = 0; i < actualListIn.size(); i++) {
  840. if (!actualExpected.get(i)) {
  841. extraListOut.add(actualListIn.get(i));
  842. }
  843. }
  844. }
  845. }
  846. // XXX unit test for makeSoftDiffs
  847. /**
  848. * Calculate potentially "soft" diffs using
  849. * Comparator.compare(expected, actual).
  850. * This shallow-copies and sorts the input Lists.
  851. * @param expectedListIn the List of expected results - treated as empty if null
  852. * @param actualListIn the List of actual results - treated as empty if null
  853. * @param extraListOut the List for any actual results not expected - ignored if null
  854. * @param missingListOut the List for any expected results not found - ignored if null
  855. * @param comparator the Comparator for comparisons - not null
  856. * @throws IllegalArgumentException if comp is null
  857. */
  858. public static void makeSoftDiffs( // XXX no intersect or union on collections???
  859. List expectedListIn,
  860. List actualListIn,
  861. List missingListOut,
  862. List extraListOut,
  863. Comparator comparator) {
  864. if ((null == missingListOut) && (null == extraListOut)) {
  865. return;
  866. }
  867. if (null == comparator) {
  868. throw new IllegalArgumentException("null comparator");
  869. }
  870. if (null == expectedListIn) {
  871. expectedListIn = Collections.EMPTY_LIST;
  872. }
  873. if (null == actualListIn) {
  874. actualListIn = Collections.EMPTY_LIST;
  875. }
  876. if ((0 == actualListIn.size()) && (0 == expectedListIn.size()) ) {
  877. return;
  878. }
  879. ArrayList expected = new ArrayList();
  880. expected.addAll(expectedListIn);
  881. Collections.sort(expected, comparator);
  882. Iterator expectedIter = expected.iterator();
  883. Object exp = null;
  884. ArrayList actual = new ArrayList();
  885. actual.addAll(actualListIn);
  886. Collections.sort(actual, comparator);
  887. Iterator actualIter = actual.iterator();
  888. Object act = null;
  889. while (((null != act) || actualIter.hasNext())
  890. && ((null != exp) || expectedIter.hasNext())) {
  891. if (null == act) {
  892. act = actualIter.next();
  893. }
  894. if (null == exp) {
  895. exp = expectedIter.next();
  896. }
  897. int diff = comparator.compare(exp, act);
  898. if (0 > diff) { // exp < act
  899. if (null != missingListOut) {
  900. missingListOut.add(exp);
  901. exp = null;
  902. }
  903. } else if (0 < diff) { // exp > act
  904. if (null != extraListOut) {
  905. extraListOut.add(act);
  906. act = null;
  907. }
  908. } else { // got match of actual to expected
  909. // absorb all actual matching expected (duplicates)
  910. while ((0 == diff) && actualIter.hasNext()) {
  911. act = actualIter.next();
  912. diff = comparator.compare(exp, act);
  913. }
  914. if (0 == diff) {
  915. act = null;
  916. }
  917. exp = null;
  918. }
  919. }
  920. if (null != missingListOut) {
  921. if (null != exp) {
  922. missingListOut.add(exp);
  923. }
  924. while (expectedIter.hasNext()) {
  925. missingListOut.add(expectedIter.next());
  926. }
  927. }
  928. if (null != extraListOut) {
  929. if (null != act) {
  930. extraListOut.add(act);
  931. }
  932. while (actualIter.hasNext()) {
  933. extraListOut.add(actualIter.next());
  934. }
  935. }
  936. }
  937. public static class FlattenSpec {
  938. /**
  939. * This tells unflatten(..) to throw IllegalArgumentException
  940. * if it finds two contiguous delimiters.
  941. */
  942. public static final String UNFLATTEN_EMPTY_ERROR
  943. = "empty items not permitted when unflattening";
  944. /**
  945. * This tells unflatten(..) to skip empty items when unflattening
  946. * (since null means "use null")
  947. */
  948. public static final String UNFLATTEN_EMPTY_AS_NULL
  949. = "unflatten empty items as null";
  950. /**
  951. * This tells unflatten(..) to skip empty items when unflattening
  952. * (since null means "use null")
  953. */
  954. public static final String SKIP_EMPTY_IN_UNFLATTEN
  955. = "skip empty items when unflattening";
  956. /**
  957. * For Ant-style attributes: "item,item" (with escaped commas).
  958. * There is no way when unflattening to distinguish
  959. * values which were empty from those which were null,
  960. * so all are unflattened as empty.
  961. */
  962. public static final FlattenSpec COMMA
  963. = new FlattenSpec(null, "", "\\", ",", null, "") {
  964. public String toString() { return "FlattenSpec.COMMA"; }
  965. };
  966. /** this attempts to mimic ((List)l).toString() */
  967. public static final FlattenSpec LIST
  968. = new FlattenSpec("[", "", null, ", ", "]", UNFLATTEN_EMPTY_ERROR) {
  969. public String toString() { return "FlattenSpec.LIST"; }
  970. };
  971. /** how toString renders null values */
  972. public static final String NULL = "<null>";
  973. private static String r(String s) {
  974. return (null == s ? NULL : s);
  975. }
  976. public final String prefix;
  977. public final String nullFlattened;
  978. public final String escape;
  979. public final String delim;
  980. public final String suffix;
  981. public final String emptyUnflattened;
  982. private transient String toString;
  983. public FlattenSpec(
  984. String prefix,
  985. String nullRendering,
  986. String escape,
  987. String delim,
  988. String suffix,
  989. String emptyUnflattened) {
  990. this.prefix = prefix;
  991. this.nullFlattened = nullRendering;
  992. this.escape = escape;
  993. this.delim = delim;
  994. this.suffix = suffix;
  995. this.emptyUnflattened = emptyUnflattened;
  996. throwIaxIfNull(emptyUnflattened, "use UNFLATTEN_EMPTY_AS_NULL");
  997. }
  998. public String toString() {
  999. if (null == toString) {
  1000. toString = "FlattenSpec("
  1001. + "prefix=" + r(prefix)
  1002. + ", nullRendering=" + r(nullFlattened)
  1003. + ", escape=" + r(escape)
  1004. + ", delim=" + r(delim)
  1005. + ", suffix=" + r(suffix)
  1006. + ", emptyUnflattened=" + r(emptyUnflattened)
  1007. + ")";
  1008. }
  1009. return toString;
  1010. }
  1011. }
  1012. } // class LangUtil
  1013. // --------- java runs using Ant
  1014. // /**
  1015. // * Run a Java command separately.
  1016. // * @param className the fully-qualified String name of the class
  1017. // * with the main method to run
  1018. // * @param classpathFiles the File to put on the classpath
  1019. // * @param args to the main method of the class
  1020. // * @param outSink the PrintStream for the output stream - may be null
  1021. // */
  1022. // public static void oldexecuteJava(
  1023. // String className,
  1024. // File[] classpathFiles,
  1025. // String[] args,
  1026. // PrintStream outSink) {
  1027. // Project project = new Project();
  1028. // project.setName("LangUtil.executeJava(" + className + ")");
  1029. // Path classpath = new Path(project, classpathFiles[0].getAbsolutePath());
  1030. // for (int i = 1; i < classpathFiles.length; i++) {
  1031. // classpath.addExisting(new Path(project, classpathFiles[i].getAbsolutePath()));
  1032. // }
  1033. //
  1034. // Commandline cmds = new Commandline();
  1035. // cmds.addArguments(new String[] {className});
  1036. // cmds.addArguments(args);
  1037. //
  1038. // ExecuteJava runner = new ExecuteJava();
  1039. // runner.setClasspath(classpath);
  1040. // runner.setJavaCommand(cmds);
  1041. // if (null != outSink) {
  1042. // runner.setOutput(outSink); // XXX todo
  1043. // }
  1044. // runner.execute(project);
  1045. // }
  1046. // public static void executeJava(
  1047. // String className,
  1048. // File dir,
  1049. // File[] classpathFiles,
  1050. // String[] args,
  1051. // PrintStream outSink) {
  1052. // StringBuffer sb = new StringBuffer();
  1053. //
  1054. // sb.append("c:/apps/jdk1.3.1/bin/java.exe -classpath \"");
  1055. // for (int i = 0; i < classpathFiles.length; i++) {
  1056. // if (i < 0) {
  1057. // sb.append(";");
  1058. // }
  1059. // sb.append(classpathFiles[i].getAbsolutePath());
  1060. // }
  1061. // sb.append("\" -verbose " + className);
  1062. // for (int i = 0; i < args.length; i++) {
  1063. // sb.append(" " + args[i]);
  1064. // }
  1065. // Exec exec = new Exec();
  1066. // Project project = new Project();
  1067. // project.setProperty("ant.home", "c:/home/wes/aj/aspectj/modules/lib/ant");
  1068. // System.setProperty("ant.home", "c:/home/wes/aj/aspectj/modules/lib/ant");
  1069. // exec.setProject(new Project());
  1070. // exec.setCommand(sb.toString());
  1071. // exec.setDir(dir.getAbsolutePath());
  1072. // exec.execute();
  1073. // }
  1074. // public static void execJavaProcess(
  1075. // String className,
  1076. // File dir,
  1077. // File[] classpathFiles,
  1078. // String[] args,
  1079. // PrintStream outSink) throws Throwable {
  1080. // StringBuffer sb = new StringBuffer();
  1081. //
  1082. // sb.append("c:\\apps\\jdk1.3.1\\bin\\java.exe -classpath \"");
  1083. // for (int i = 0; i < classpathFiles.length; i++) {
  1084. // if (i > 0) {
  1085. // sb.append(";");
  1086. // }
  1087. // sb.append(classpathFiles[i].getAbsolutePath());
  1088. // }
  1089. // sb.append("\" -verbose " + className);
  1090. // for (int i = 0; i < args.length; i++) {
  1091. // sb.append(" " + args[i]);
  1092. // }
  1093. // String command = sb.toString();
  1094. // System.err.println("launching process: " + command);
  1095. // Process process = Runtime.getRuntime().exec(command);
  1096. // // huh? err/out
  1097. // InputStream errStream = null;
  1098. // InputStream outStream = null;
  1099. // Throwable toThrow = null;
  1100. // int result = -1;
  1101. // try {
  1102. // System.err.println("waiting for process: " + command);
  1103. // errStream = null; // process.getErrorStream();
  1104. // outStream = null; // process.getInputStream(); // misnamed - out
  1105. // result = process.waitFor();
  1106. // System.err.println("Done waiting for process: " + command);
  1107. // process.destroy();
  1108. // } catch (Throwable t) {
  1109. // toThrow = t;
  1110. // } finally {
  1111. // if (null != outStream) {
  1112. // FileUtil.copy(outStream, System.out, false);
  1113. // try { outStream.close(); }
  1114. // catch (IOException e) {}
  1115. // }
  1116. // if (null != errStream) {
  1117. // FileUtil.copy(errStream, System.err, false);
  1118. // try { errStream.close(); }
  1119. // catch (IOException e) {}
  1120. // }
  1121. // }
  1122. // if (null != toThrow) {
  1123. // throw toThrow;
  1124. // }
  1125. // }
  1126. // try {
  1127. // // show the command
  1128. // log(command, Project.MSG_VERBOSE);
  1129. //
  1130. // // exec command on system runtime
  1131. // Process proc = Runtime.getRuntime().exec(command);
  1132. //
  1133. // if (out != null) {
  1134. // fos = new PrintWriter(new FileWriter(out));
  1135. // log("Output redirected to " + out, Project.MSG_VERBOSE);
  1136. // }
  1137. //
  1138. // // copy input and error to the output stream
  1139. // StreamPumper inputPumper =
  1140. // new StreamPumper(proc.getInputStream(), Project.MSG_INFO);
  1141. // StreamPumper errorPumper =
  1142. // new StreamPumper(proc.getErrorStream(), Project.MSG_WARN);
  1143. //
  1144. // // starts pumping away the generated output/error
  1145. // inputPumper.start();
  1146. // errorPumper.start();
  1147. //
  1148. // // Wait for everything to finish
  1149. // proc.waitFor();
  1150. // inputPumper.join();
  1151. // errorPumper.join();
  1152. // proc.destroy();
  1153. //
  1154. // // close the output file if required
  1155. // logFlush();
  1156. //
  1157. // // check its exit value
  1158. // err = proc.exitValue();
  1159. // if (err != 0) {
  1160. // if (failOnError) {
  1161. // throw new BuildException("Exec returned: " + err, getLocation());
  1162. // } else {
  1163. // log("Result: " + err, Project.MSG_ERR);
  1164. // }
  1165. // }
  1166. // } catch (IOException ioe) {
  1167. // throw new BuildException("Error exec: " + command, ioe, getLocation());
  1168. // } catch (InterruptedException ex) {}
  1169. //