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.

TestUtil.java 34KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999
  1. /* *******************************************************************
  2. * Copyright (c) 2002 Palo Alto Research Center, Incorporated (PARC).
  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 java.io.BufferedReader;
  14. import java.io.ByteArrayOutputStream;
  15. import java.io.DataInputStream;
  16. import java.io.File;
  17. import java.io.FileInputStream;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.io.PrintStream;
  21. import java.io.PrintWriter;
  22. import java.io.StringReader;
  23. import java.io.StringWriter;
  24. import java.lang.reflect.InvocationTargetException;
  25. import java.lang.reflect.Method;
  26. import java.lang.reflect.Modifier;
  27. import java.net.MalformedURLException;
  28. import java.net.URL;
  29. import java.util.ArrayList;
  30. import java.util.Arrays;
  31. import java.util.Collection;
  32. import java.util.Collections;
  33. import java.util.Enumeration;
  34. import java.util.HashMap;
  35. import java.util.HashSet;
  36. import java.util.Iterator;
  37. import java.util.List;
  38. import java.util.Map;
  39. import java.util.Properties;
  40. import java.util.Set;
  41. import jdiff.text.FileLine;
  42. import jdiff.util.Diff;
  43. import jdiff.util.DiffNormalOutput;
  44. import junit.framework.Assert;
  45. import junit.framework.Test;
  46. import junit.framework.TestCase;
  47. import junit.framework.TestResult;
  48. import junit.framework.TestSuite;
  49. import junit.runner.TestCaseClassLoader;
  50. import org.aspectj.bridge.IMessageHandler;
  51. import org.aspectj.bridge.MessageUtil;
  52. import org.aspectj.util.FileUtil;
  53. import org.aspectj.util.LangUtil;
  54. import org.aspectj.util.Reflection;
  55. /**
  56. * Things that junit should perhaps have, but doesn't. Note the file-comparison
  57. * methods require JDiff to run, but JDiff types are not required to resolve
  58. * this class. Also, the bytecode weaver is required to compare class files, but
  59. * not to compare other files.
  60. */
  61. public final class TestUtil {
  62. private static final String ASPECTJRT_KEY = "aspectjrt";
  63. private static final String TESTING_CLIENT_KEY = "testing-client";
  64. public static final URL BAD_URL;
  65. private static final File LIB_DIR;
  66. private static final Properties LIB_RPATHS;
  67. private static final Map LIB_ENTRIES;
  68. static {
  69. {
  70. URL url = null;
  71. try {
  72. url = new URL("http://eclipse.org/BADURL");
  73. } catch (MalformedURLException e) {
  74. // ignore - hopefully never
  75. }
  76. BAD_URL = url;
  77. }
  78. {
  79. File file = new File("lib");
  80. if (!isLibDir(file)) {
  81. File cur = new File(".").getAbsoluteFile();
  82. File parent = cur.getParentFile();
  83. while (null != parent) {
  84. file = new File(parent, "lib");
  85. if (isLibDir(file)) {
  86. break;
  87. }
  88. parent = parent.getParentFile();
  89. }
  90. if (null == parent) {
  91. file = new File("NOT IN ASPECTJ TREE");
  92. }
  93. }
  94. LIB_DIR = file;
  95. }
  96. LIB_RPATHS = new Properties();
  97. LIB_RPATHS.setProperty(ASPECTJRT_KEY, "tests/aspectjrt.jar");
  98. LIB_RPATHS.setProperty(TESTING_CLIENT_KEY, "tests/testing-client.jar");
  99. // TODO support others loaded dynamically
  100. Map map = new HashMap();
  101. for (Iterator iter = LIB_RPATHS.keySet().iterator(); iter.hasNext();) {
  102. String key = (String) iter.next();
  103. String path = LIB_RPATHS.getProperty(key);
  104. File file = null;
  105. URL url = null;
  106. try {
  107. file = libFile(path);
  108. url = libURL(path);
  109. } catch (IllegalArgumentException e) {
  110. file = new File(path + " not found");
  111. url = BAD_URL;
  112. } finally {
  113. map.put(key + ".file", file);
  114. map.put(key + ".url", url);
  115. }
  116. }
  117. // TODO support changing entries, etc.
  118. LIB_ENTRIES = Collections.unmodifiableMap(map);
  119. }
  120. private static boolean isLibDir(File lib) {
  121. return new File(lib, "test" + File.separator + "aspectjrt.jar").exists();
  122. }
  123. private TestUtil() {
  124. super();
  125. }
  126. public static URL fileToURL(File file) {
  127. try {
  128. return file.toURL();
  129. } catch (MalformedURLException e) {
  130. return null;
  131. }
  132. }
  133. public static String filesToPath(File[] entries) {
  134. return toPath(entries);
  135. }
  136. public static String urlsToPath(URL[] entries) {
  137. return toPath(entries);
  138. }
  139. /**
  140. * untyped interface for mixed entries
  141. */
  142. public static String filesOrurlsToPath(Object[] entries) {
  143. return toPath(entries);
  144. }
  145. /**
  146. * This relies on these being File (where toString() == getPath())
  147. * or URL (where toString() == toExternalForm()).
  148. * @param entries the Object[] of File or URL elements
  149. * @return the String with entries dlimited by the File.pathSeparator
  150. */
  151. private static String toPath(Object[] entries) {
  152. if ((null == entries) || (0 == entries.length)) {
  153. return "";
  154. }
  155. StringBuffer path = new StringBuffer();
  156. boolean started = false;
  157. for (int i = 0; i < entries.length; i++) {
  158. if (null != entries[i]) {
  159. if (started) {
  160. path.append(File.pathSeparator);
  161. } else {
  162. started = true;
  163. }
  164. path.append(entries[i].toString());
  165. }
  166. }
  167. return path.toString();
  168. }
  169. /**
  170. * @param s the String to parse for [on|off|true|false]
  171. * @throws IllegalArgumentException if input is bad
  172. **/
  173. public static boolean parseBoolean(String input) {
  174. return parseBoolean(input, true);
  175. }
  176. /**
  177. * @param s the String to parse for [on|off|true|false]
  178. * @param iaxOnError if true and input is bad, throw
  179. * IllegalArgumentException
  180. * @return true if input is true, false otherwise
  181. * @throws IllegalArgumentException if iaxOnError and input is bad
  182. */
  183. public static boolean parseBoolean(final String input, boolean iaxOnError) {
  184. final String syntax = ": [on|off|true|false]";
  185. if (null == input) {
  186. return false;
  187. }
  188. String lc = input.trim().toLowerCase();
  189. boolean result = false;
  190. boolean valid = false;
  191. switch (lc.length()) {
  192. case 2:
  193. if (valid = "on".equals(lc)) {
  194. result = true;
  195. }
  196. break;
  197. case 3:
  198. valid = "off".equals(lc);
  199. break;
  200. case 4:
  201. if (valid = "true".equals(lc)) {
  202. result = true;
  203. }
  204. break;
  205. case 5:
  206. valid = "false".equals(lc);
  207. break;
  208. }
  209. if (iaxOnError && !valid) {
  210. throw new IllegalArgumentException(input + syntax);
  211. }
  212. return result;
  213. }
  214. public static File aspectjrtJarFile() {
  215. return (File) LIB_ENTRIES.get(ASPECTJRT_KEY + ".file");
  216. }
  217. public static URL aspectjrtJarURL() {
  218. return (URL) LIB_ENTRIES.get(ASPECTJRT_KEY + ".url");
  219. }
  220. public static File testingClientJarFile() {
  221. return (File) LIB_ENTRIES.get(TESTING_CLIENT_KEY + ".file");
  222. }
  223. public static URL testingClientJarURL() {
  224. return (URL) LIB_ENTRIES.get(TESTING_CLIENT_KEY + ".url");
  225. }
  226. /**
  227. *
  228. * @param rpath the String relative path from the library directory
  229. * to a resource that must exist (may be a directory),
  230. * using forward slashes as a file separator
  231. * @return the File path
  232. * @throws IllegalArgumentException if no such directory or file
  233. */
  234. public static File libFile(String rpath) {
  235. if ((null == rpath) || (0 == rpath.length())) {
  236. throw new IllegalArgumentException("no input");
  237. }
  238. rpath = rpath.replace('/', File.separatorChar);
  239. File result = new File(LIB_DIR, rpath);
  240. if (result.exists()) {
  241. return result;
  242. }
  243. throw new IllegalArgumentException("not in " + LIB_DIR + ": " + rpath);
  244. }
  245. /**
  246. * Like libPath, only it returns a URL.
  247. * @return URL or null if it does not exist
  248. * @throws IllegalArgumentException if no such directory or file
  249. */
  250. public static URL libURL(String rpath) {
  251. File file = libFile(rpath);
  252. try {
  253. return file.toURL();
  254. } catch (MalformedURLException e) {
  255. throw new IllegalArgumentException("bad URL from: " + file);
  256. }
  257. }
  258. // ---- arrays
  259. public static void assertArrayEquals(String msg, Object[] expected,
  260. Object[] found) {
  261. TestCase.assertEquals(msg, Arrays.asList(expected), Arrays
  262. .asList(found));
  263. }
  264. // ---- unordered
  265. public static void assertSetEquals(Collection expected, Collection found) {
  266. assertSetEquals(null, expected, found);
  267. }
  268. public static void assertSetEquals(String msg, Object[] expected,
  269. Object[] found) {
  270. assertSetEquals(msg, Arrays.asList(expected), Arrays.asList(found));
  271. }
  272. public static void assertSetEquals(String msg, Collection expected,
  273. Collection found) {
  274. msg = (msg == null) ? "" : msg + ": ";
  275. Set results1 = new HashSet(found);
  276. results1.removeAll(expected);
  277. Set results2 = new HashSet(expected);
  278. results2.removeAll(found);
  279. if (results1.isEmpty()) {
  280. TestCase.assertTrue(msg + "Expected but didn't find: "
  281. + results2.toString(), results2.isEmpty());
  282. } else if (results2.isEmpty()) {
  283. TestCase.assertTrue(msg + "Didn't expect: " + results1.toString(),
  284. results1.isEmpty());
  285. } else {
  286. TestCase.assertTrue(msg + "Expected but didn't find: "
  287. + results2.toString() + "\nDidn't expect: "
  288. + results1.toString(), false);
  289. }
  290. }
  291. // ---- objects
  292. public static void assertCommutativeEquals(Object a, Object b,
  293. boolean should) {
  294. TestCase.assertEquals(a + " equals " + b, should, a.equals(b));
  295. TestCase.assertEquals(b + " equals " + a, should, b.equals(a));
  296. assertHashEquals(a, b, should);
  297. }
  298. private static void assertHashEquals(Object s, Object t, boolean should) {
  299. if (should) {
  300. TestCase.assertTrue(s + " does not hash to same as " + t, s
  301. .hashCode() == t.hashCode());
  302. } else {
  303. if (s.hashCode() == t.hashCode()) {
  304. System.err.println("warning: hash collision with hash = "
  305. + t.hashCode());
  306. System.err.println(" for " + s);
  307. System.err.println(" and " + t);
  308. }
  309. }
  310. }
  311. // -- reflective stuff
  312. public static void runMain(String classPath, String className) {
  313. runMethod(classPath, className, "main", new Object[] { new String[0] });
  314. }
  315. public static Object runMethod(String classPath, String className,
  316. String methodName, Object[] args) {
  317. classPath += File.pathSeparator + System.getProperty("java.class.path");
  318. ClassLoader loader = new TestCaseClassLoader(classPath);
  319. Class c = null;
  320. try {
  321. c = loader.loadClass(className);
  322. } catch (ClassNotFoundException e) {
  323. Assert.assertTrue("unexpected exception: " + e, false);
  324. }
  325. return Reflection.invokestaticN(c, methodName, args);
  326. }
  327. /**
  328. * Checks that two multi-line strings have the same value. Each line is
  329. * trimmed before comparision Produces an error on the particular line of
  330. * conflict
  331. */
  332. public static void assertMultiLineStringEquals(String message, String s1,
  333. String s2) {
  334. try {
  335. BufferedReader r1 = new BufferedReader(new StringReader(s1));
  336. BufferedReader r2 = new BufferedReader(new StringReader(s2));
  337. List lines = new ArrayList();
  338. String l1, l2;
  339. int index = 1;
  340. while (true) {
  341. l1 = readNonBlankLine(r1);
  342. l2 = readNonBlankLine(r2);
  343. if (l1 == null || l2 == null)
  344. break;
  345. if (l1.equals(l2)) {
  346. lines.add(l1);
  347. } else {
  348. showContext(lines);
  349. Assert.assertEquals(message + "(line " + index + ")", l1,
  350. l2);
  351. }
  352. index++;
  353. }
  354. if (l1 != null)
  355. showContext(lines);
  356. Assert.assertTrue(message + ": unexpected " + l1, l1 == null);
  357. if (l2 != null)
  358. showContext(lines);
  359. Assert.assertTrue(message + ": unexpected " + l2, l2 == null);
  360. } catch (IOException ioe) {
  361. Assert.assertTrue(message + ": caught " + ioe.getMessage(), false);
  362. }
  363. }
  364. private static void showContext(List lines) {
  365. int n = lines.size();
  366. for (int i = Math.max(0, n - 8); i < n; i++) {
  367. System.err.println(lines.get(i));
  368. }
  369. }
  370. private static String readNonBlankLine(BufferedReader r) throws IOException {
  371. String l = r.readLine();
  372. if (l == null)
  373. return null;
  374. l = l.trim();
  375. // comment to include comments when reading
  376. int commentLoc = l.indexOf("//");
  377. if (-1 != commentLoc) {
  378. l = l.substring(0, commentLoc).trim();
  379. }
  380. if ("".equals(l))
  381. return readNonBlankLine(r);
  382. return l;
  383. }
  384. /**
  385. * If there is an expected dir, expect each file in its subtree to match a
  386. * corresponding actual file in the base directory. This does NOT check that
  387. * all actual files have corresponding expected files. This ignores
  388. * directory paths containing "CVS".
  389. *
  390. * @param handler
  391. * the IMessageHandler sink for error messages
  392. * @param expectedBaseDir
  393. * the File path to the directory containing expected files, all
  394. * of which are compared with any corresponding actual files
  395. * @param actualBaseDir
  396. * the File path to the base directory from which to find any
  397. * actual files corresponding to expected files.
  398. * @return true if all files in the expectedBaseDir directory tree have
  399. * matching files in the actualBaseDir directory tree.
  400. */
  401. public static boolean sameDirectoryContents(final IMessageHandler handler,
  402. final File expectedBaseDir, final File actualBaseDir,
  403. final boolean fastFail) {
  404. LangUtil.throwIaxIfNull(handler, "handler");
  405. if (!FileUtil.canReadDir(expectedBaseDir)) {
  406. MessageUtil.fail(handler, " expected dir not found: "
  407. + expectedBaseDir);
  408. return false;
  409. }
  410. if (!FileUtil.canReadDir(actualBaseDir)) {
  411. MessageUtil
  412. .fail(handler, " actual dir not found: " + actualBaseDir);
  413. return false;
  414. }
  415. String[] paths = FileUtil.listFiles(expectedBaseDir);
  416. boolean result = true;
  417. for (int i = 0; i < paths.length; i++) {
  418. if (-1 != paths[i].indexOf("CVS")) {
  419. continue;
  420. }
  421. if (!sameFiles(handler, expectedBaseDir, actualBaseDir, paths[i])
  422. && result) {
  423. result = false;
  424. if (fastFail) {
  425. break;
  426. }
  427. }
  428. }
  429. return result;
  430. }
  431. // ------------ File-comparison utilities (XXX need their own class...)
  432. /**
  433. * Test interface to compare two files, line by line, and report differences
  434. * as one FAIL message if a handler is supplied. This preprocesses .class
  435. * files by disassembling.
  436. *
  437. * @param handler
  438. * the IMessageHandler for any FAIL messages (null to ignore)
  439. * @param expectedFile
  440. * the File path to the canonical file
  441. * @param actualFile
  442. * the File path to the actual file, if any
  443. * @return true if the input files are the same, based on per-line
  444. * comparisons
  445. */
  446. public static boolean sameFiles(IMessageHandler handler, File expectedFile,
  447. File actualFile) {
  448. return doSameFile(handler, null, null, expectedFile, actualFile);
  449. }
  450. /**
  451. * Test interface to compare two files, line by line, and report differences
  452. * as one FAIL message if a handler is supplied. This preprocesses .class
  453. * files by disassembling. This method assumes that the files are at the
  454. * same offset from two respective base directories.
  455. *
  456. * @param handler
  457. * the IMessageHandler for any FAIL messages (null to ignore)
  458. * @param expectedBaseDir
  459. * the File path to the canonical file base directory
  460. * @param actualBaseDir
  461. * the File path to the actual file base directory
  462. * @param path
  463. * the String path offset from the base directories
  464. * @return true if the input files are the same, based on per-line
  465. * comparisons
  466. */
  467. public static boolean sameFiles(IMessageHandler handler,
  468. File expectedBaseDir, File actualBaseDir, String path) {
  469. File actualFile = new File(actualBaseDir, path);
  470. File expectedFile = new File(expectedBaseDir, path);
  471. return doSameFile(handler, expectedBaseDir, actualBaseDir,
  472. expectedFile, actualFile);
  473. }
  474. /**
  475. * This does the work, selecting a lineator subclass and converting public
  476. * API's to JDiff APIs for comparison. Currently, all jdiff interfaces are
  477. * method-local, so this class will load without it; if we do use it, we can
  478. * avoid the duplication.
  479. */
  480. private static boolean doSameFile(IMessageHandler handler,
  481. File expectedBaseDir, File actualBaseDir, File expectedFile,
  482. File actualFile) {
  483. String path = expectedFile.getPath();
  484. // XXX permit user to specify lineator
  485. ILineator lineator = Lineator.TEXT;
  486. if (path.endsWith(".class")) {
  487. if (ClassLineator.haveDisassembler()) {
  488. lineator = Lineator.CLASS;
  489. } else {
  490. MessageUtil.abort(handler,
  491. "skipping - dissassembler not available");
  492. return false;
  493. }
  494. }
  495. CanonicalLine[] actualLines = null;
  496. CanonicalLine[] expectedLines = null;
  497. try {
  498. actualLines = lineator.getLines(handler, actualFile, actualBaseDir);
  499. expectedLines = lineator.getLines(handler, expectedFile,
  500. expectedBaseDir);
  501. } catch (IOException e) {
  502. MessageUtil.fail(handler, "rendering lines ", e);
  503. return false;
  504. }
  505. if (!LangUtil.isEmpty(actualLines) && !LangUtil.isEmpty(expectedLines)) {
  506. // here's the transmutation back to jdiff - extract if publishing
  507. // JDiff
  508. CanonicalLine[][] clines = new CanonicalLine[][] { expectedLines,
  509. actualLines };
  510. FileLine[][] flines = new FileLine[2][];
  511. for (int i = 0; i < clines.length; i++) {
  512. CanonicalLine[] cline = clines[i];
  513. FileLine[] fline = new FileLine[cline.length];
  514. for (int j = 0; j < fline.length; j++) {
  515. fline[j] = new FileLine(cline[j].canonical, cline[j].line);
  516. }
  517. flines[i] = fline;
  518. }
  519. Diff.change edits = new Diff(flines[0], flines[1]).diff_2(false);
  520. if ((null == edits) || (0 == (edits.inserted + edits.deleted))) {
  521. // XXX confirm with jdiff that null means no edits
  522. return true;
  523. } else {
  524. // String m = render(handler, edits, flines[0], flines[1]);
  525. StringWriter writer = new StringWriter();
  526. DiffNormalOutput out = new DiffNormalOutput(flines[0],
  527. flines[1]);
  528. out.setOut(writer);
  529. out.setLineSeparator(LangUtil.EOL);
  530. try {
  531. out.writeScript(edits);
  532. } catch (IOException e) {
  533. MessageUtil.fail(handler, "rendering edits", e);
  534. } finally {
  535. if (null != writer) {
  536. try {
  537. writer.close();
  538. } catch (IOException e) {
  539. MessageUtil.fail(handler,
  540. "closing after rendering edits", e);
  541. }
  542. }
  543. }
  544. String message = "diff between " + path + " in expected dir "
  545. + expectedBaseDir + " and actual dir " + actualBaseDir
  546. + LangUtil.EOL + writer.toString();
  547. MessageUtil.fail(handler, message);
  548. }
  549. }
  550. return false;
  551. }
  552. /**
  553. * TODO move to testing-utils for use by loadtime5, others.
  554. *
  555. * @param sink
  556. * @param sourceName
  557. */
  558. public static void loadTestsReflectively(TestSuite sink, String sourceName, boolean ignoreError) {
  559. Throwable thrown = null;
  560. try {
  561. ClassLoader loader = sink.getClass().getClassLoader();
  562. Class sourceClass = loader.loadClass(sourceName);
  563. if (!Modifier.isPublic(sourceClass.getModifiers())) {
  564. errorSuite(sink, sourceName, "not public class");
  565. return;
  566. }
  567. Method suiteMethod = sourceClass.getMethod("suite", new Class[0]);
  568. int mods = suiteMethod.getModifiers();
  569. if (!Modifier.isStatic(mods) || !Modifier.isPublic(mods)) {
  570. errorSuite(sink, sourceName, "not static method");
  571. return;
  572. }
  573. if (!Modifier.isPublic(mods)) {
  574. errorSuite(sink, sourceName, "not public method");
  575. return;
  576. }
  577. if (!Test.class.isAssignableFrom(suiteMethod.getReturnType())) {
  578. errorSuite(sink, sourceName, "suite() does not return Test");
  579. return;
  580. }
  581. Object result = suiteMethod.invoke(null, new Object[0]);
  582. Test test = (Test) result;
  583. if (!(test instanceof TestSuite)) {
  584. sink.addTest(test);
  585. } else {
  586. TestSuite source = (TestSuite) test;
  587. Enumeration tests = source.tests();
  588. while (tests.hasMoreElements()) {
  589. sink.addTest((Test) tests.nextElement());
  590. }
  591. }
  592. } catch (ClassNotFoundException e) {
  593. thrown = e;
  594. } catch (SecurityException e) {
  595. thrown = e;
  596. } catch (NoSuchMethodException e) {
  597. thrown = e;
  598. } catch (IllegalArgumentException e) {
  599. thrown = e;
  600. } catch (IllegalAccessException e) {
  601. thrown = e;
  602. } catch (InvocationTargetException e) {
  603. thrown = e;
  604. }
  605. if (null != thrown) {
  606. if (ignoreError) {
  607. System.err.println("Error loading " + sourceName);
  608. thrown.printStackTrace(System.err);
  609. } else {
  610. errorSuite(sink, sourceName, thrown);
  611. }
  612. }
  613. }
  614. private static void errorSuite(TestSuite sink, String sourceName,
  615. Throwable thrown) {
  616. sink.addTest(new ErrorTest(sourceName, thrown));
  617. }
  618. private static void errorSuite(TestSuite sink, String sourceName, String err) {
  619. String message = "bad " + sourceName + ": " + err;
  620. sink.addTest(new ErrorTest(message));
  621. }
  622. /**
  623. * Junit test failure, e.g., to report suite initialization errors at test time.
  624. */
  625. public static class ErrorTest implements Test {
  626. private final Throwable thrown;
  627. public ErrorTest(Throwable thrown) {
  628. this.thrown = thrown;
  629. }
  630. public ErrorTest(String message) {
  631. this.thrown = new Error(message);
  632. }
  633. public ErrorTest(String message, Throwable thrown) {
  634. this(new TestError(message, thrown));
  635. }
  636. public int countTestCases() {
  637. return 1;
  638. }
  639. public void run(TestResult result) {
  640. result.startTest(this);
  641. result.addError(this, thrown);
  642. }
  643. }
  644. /**
  645. * Nested exception - remove when using 1.4 or later.
  646. */
  647. public static class TestError extends Error {
  648. private Throwable thrown;
  649. public TestError(String message) {
  650. super(message);
  651. }
  652. public TestError(String message, Throwable thrown) {
  653. super(message);
  654. this.thrown = thrown;
  655. }
  656. public Throwable getCause() {
  657. return thrown;
  658. }
  659. public void printStackTrace() {
  660. printStackTrace(System.err);
  661. }
  662. public void printStackTrace(PrintStream ps) {
  663. printStackTrace(new PrintWriter(ps));
  664. }
  665. public void printStackTrace(PrintWriter pw) {
  666. super.printStackTrace(pw);
  667. if (null != thrown) {
  668. pw.print("Caused by: ");
  669. thrown.printStackTrace(pw);
  670. }
  671. }
  672. }
  673. /** component that reduces file to CanonicalLine[] */
  674. public static interface ILineator {
  675. /** Lineator suitable for text files */
  676. public static final ILineator TEXT = new TextLineator();
  677. /** Lineator suitable for class files (disassembles first) */
  678. public static final ILineator CLASS = new ClassLineator();
  679. /**
  680. * Reduce file to CanonicalLine[].
  681. *
  682. * @param handler
  683. * the IMessageHandler for errors (may be null)
  684. * @param file
  685. * the File to render
  686. * @param basedir
  687. * the File for the base directory (may be null)
  688. * @return CanonicalLine[] of lines - not null, but perhaps empty
  689. */
  690. CanonicalLine[] getLines(IMessageHandler handler, File file,
  691. File basedir) throws IOException;
  692. }
  693. /** alias for jdiff FileLine to avoid client binding */
  694. public static class CanonicalLine {
  695. public static final CanonicalLine[] NO_LINES = new CanonicalLine[0];
  696. /** canonical variant of line for comparison */
  697. public final String canonical;
  698. /** actual line, for logging */
  699. public final String line;
  700. public CanonicalLine(String canonical, String line) {
  701. this.canonical = canonical;
  702. this.line = line;
  703. }
  704. public String toString() {
  705. return line;
  706. }
  707. }
  708. private abstract static class Lineator implements ILineator {
  709. /**
  710. * Reduce file to CanonicalLine[].
  711. *
  712. * @param handler
  713. * the IMessageHandler for errors (may be null)
  714. * @param file
  715. * the File to render
  716. * @param basedir
  717. * the File for the base directory (may be null)
  718. */
  719. public CanonicalLine[] getLines(IMessageHandler handler, File file,
  720. File basedir) throws IOException {
  721. if (!file.canRead() || !file.isFile()) {
  722. MessageUtil.error(handler, "not readable file: " + basedir
  723. + " - " + file);
  724. return null;
  725. }
  726. // capture file as FileLine[]
  727. InputStream in = null;
  728. /* String path = */FileUtil.normalizedPath(file, basedir);
  729. LineStream capture = new LineStream();
  730. try {
  731. lineate(capture, handler, basedir, file);
  732. } catch (IOException e) {
  733. MessageUtil
  734. .fail(handler,
  735. "NormalizedCompareFiles IOException reading "
  736. + file, e);
  737. return null;
  738. } finally {
  739. if (null != in) {
  740. try {
  741. in.close();
  742. } catch (IOException e) {
  743. } // ignore
  744. }
  745. capture.flush();
  746. capture.close();
  747. }
  748. String missed = capture.getMissed();
  749. if (!LangUtil.isEmpty(missed)) {
  750. MessageUtil.warn(handler,
  751. "NormalizedCompareFiles missed input: " + missed);
  752. return null;
  753. } else {
  754. String[] lines = capture.getLines();
  755. CanonicalLine[] result = new CanonicalLine[lines.length];
  756. for (int i = 0; i < lines.length; i++) {
  757. result[i] = new CanonicalLine(lines[i], lines[i]);
  758. }
  759. return result;
  760. }
  761. }
  762. protected abstract void lineate(PrintStream sink,
  763. IMessageHandler handler, File basedir, File file)
  764. throws IOException;
  765. }
  766. private static class TextLineator extends Lineator {
  767. protected void lineate(PrintStream sink, IMessageHandler handler,
  768. File basedir, File file) throws IOException {
  769. InputStream in = null;
  770. try {
  771. in = new FileInputStream(file);
  772. FileUtil.copyStream(new DataInputStream(in), sink);
  773. } finally {
  774. try {
  775. in.close();
  776. } catch (IOException e) {
  777. } // ignore
  778. }
  779. }
  780. }
  781. public static class ClassLineator extends Lineator {
  782. protected void lineate(PrintStream sink, IMessageHandler handler,
  783. File basedir, File file) throws IOException {
  784. String name = FileUtil.fileToClassName(basedir, file);
  785. // XXX re-enable preflight?
  786. // if ((null != basedir) && (path.length()-6 != name.length())) {
  787. // MessageUtil.error(handler, "unexpected class name \""
  788. // + name + "\" for path " + path);
  789. // return null;
  790. // }
  791. disassemble(handler, basedir, name, sink);
  792. }
  793. public static boolean haveDisassembler() {
  794. try {
  795. return (null != Class
  796. .forName("org.aspectj.weaver.bcel.LazyClassGen"));
  797. } catch (ClassNotFoundException e) {
  798. // XXX fix
  799. // System.err.println(e.getMessage());
  800. // e.printStackTrace(System.err);
  801. return false;
  802. }
  803. }
  804. /** XXX dependency on bcweaver/bcel */
  805. private static void disassemble(IMessageHandler handler, File basedir,
  806. String name, PrintStream out) throws IOException {
  807. // LazyClassGen.disassemble(FileUtil.normalizedPath(basedir), name,
  808. // capture);
  809. Throwable thrown = null;
  810. String basedirPath = FileUtil.normalizedPath(basedir);
  811. // XXX use reflection utilities to invoke dissassembler?
  812. try {
  813. // XXX need test to detect when this is refactored
  814. Class c = Class.forName("org.aspectj.weaver.bcel.LazyClassGen");
  815. Method m = c.getMethod("disassemble", new Class[] {
  816. String.class, String.class, PrintStream.class });
  817. m.invoke(null, new Object[] { basedirPath, name, out });
  818. } catch (ClassNotFoundException e) {
  819. thrown = e;
  820. } catch (NoSuchMethodException e) {
  821. thrown = e;
  822. } catch (IllegalAccessException e) {
  823. thrown = e;
  824. } catch (InvocationTargetException e) {
  825. Throwable t = e.getTargetException();
  826. if (t instanceof IOException) {
  827. throw (IOException) t;
  828. }
  829. thrown = t;
  830. }
  831. if (null != thrown) {
  832. MessageUtil.fail(handler, "disassembling " + name + " path: "
  833. + basedirPath, thrown);
  834. }
  835. }
  836. }
  837. /**
  838. * Capture PrintStream output to String[] (delimiting component String on
  839. * println()), also showing any missed text.
  840. */
  841. public static class LineStream extends PrintStream {
  842. StringBuffer sb = new StringBuffer();
  843. ByteArrayOutputStream missed;
  844. ArrayList sink;
  845. public LineStream() {
  846. super(new ByteArrayOutputStream());
  847. this.sink = new ArrayList();
  848. missed = (ByteArrayOutputStream) out;
  849. }
  850. /** @return any text not captured by our overrides */
  851. public String getMissed() {
  852. return missed.toString();
  853. }
  854. /** clear captured lines (but not missed text) */
  855. public void clear() {
  856. sink.clear();
  857. }
  858. /**
  859. * Get String[] of lines printed, delimited by println(..) calls.
  860. *
  861. * @return lines printed, exclusive of any not yet terminated by newline
  862. */
  863. public String[] getLines() {
  864. return (String[]) sink.toArray(new String[0]);
  865. }
  866. // ---------- PrintStream overrides
  867. public void println(Object x) {
  868. println(x.toString());
  869. }
  870. public void print(Object obj) {
  871. print(obj.toString());
  872. }
  873. public void println(char c) {
  874. sb.append(c);
  875. println();
  876. }
  877. public void println(char[] c) {
  878. sb.append(c);
  879. println();
  880. }
  881. public void print(char c) {
  882. sb.append(c);
  883. }
  884. public void print(char[] c) {
  885. sb.append(c);
  886. }
  887. public void println(String s) {
  888. print(s);
  889. println();
  890. }
  891. public void print(String s) {
  892. sb.append(s);
  893. }
  894. public void println() {
  895. String line = sb.toString();
  896. sink.add(line);
  897. sb.setLength(0);
  898. }
  899. }
  900. }