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.

FileUtilTest.java 25KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. /* *******************************************************************
  2. * Copyright (c) 1999-2001 Xerox Corporation,
  3. * 2002 Palo Alto Research Center, Incorporated (PARC).
  4. * All rights reserved.
  5. * This program and the accompanying materials are made available
  6. * under the terms of the Eclipse Public License v1.0
  7. * which accompanies this distribution and is available at
  8. * http://www.eclipse.org/legal/epl-v10.html
  9. *
  10. * Contributors:
  11. * Xerox/PARC initial implementation
  12. * ******************************************************************/
  13. package org.aspectj.util;
  14. //import java.io.ByteArrayInputStream;
  15. import java.io.ByteArrayOutputStream;
  16. import java.io.File;
  17. import java.io.FilenameFilter;
  18. import java.io.IOException;
  19. import java.io.InputStream;
  20. import java.io.OutputStream;
  21. import java.io.PrintStream;
  22. import java.io.StringBufferInputStream;
  23. import java.net.URL;
  24. import java.util.ArrayList;
  25. import java.util.Arrays;
  26. import java.util.Collections;
  27. import java.util.Iterator;
  28. import java.util.List;
  29. import java.util.ListIterator;
  30. import junit.framework.TestCase;
  31. import junit.textui.TestRunner;
  32. /**
  33. *
  34. */
  35. public class FileUtilTest extends TestCase {
  36. public static final String[] NONE = new String[0];
  37. public static boolean log = false;
  38. public static void main(String[] args) {
  39. TestRunner.main(new String[] {"org.aspectj.util.FileUtilTest"});
  40. }
  41. public static void assertSame(String prefix, String[] lhs, String[] rhs) { // XXX cheap diff
  42. String srcPaths = LangUtil.arrayAsList(lhs).toString();
  43. String destPaths = LangUtil.arrayAsList(rhs).toString();
  44. if (!srcPaths.equals(destPaths)) {
  45. log("expected: " + srcPaths);
  46. log(" actual: " + destPaths);
  47. assertTrue(prefix + " expected=" + srcPaths
  48. + " != actual=" + destPaths, false);
  49. }
  50. }
  51. /**
  52. * Verify that dir contains files with names,
  53. * and return the names of other files in dir.
  54. * @return the contents of dir after excluding files
  55. * or NONE if none
  56. * @throws AssertionFailedError if any names are not in dir
  57. */
  58. public static String[] dirContains(File dir, final String[] filenames) {
  59. final ArrayList sought
  60. = new ArrayList(LangUtil.arrayAsList(filenames));
  61. FilenameFilter filter = new FilenameFilter() {
  62. public boolean accept(File d, String name) {
  63. return !sought.remove(name);
  64. }
  65. };
  66. // remove any found from sought and return remainder
  67. String[] found = dir.list(filter);
  68. if (0 < sought.size()) {
  69. assertTrue("found "+ LangUtil.arrayAsList(dir.list()).toString()
  70. + " expected " + sought, false);
  71. }
  72. return (found.length == 0 ? NONE : found);
  73. }
  74. /** @return sorted String[] of all paths to all files/dirs under dir */
  75. public static String[] dirPaths(File dir) {
  76. return dirPaths(dir, new String[0]);
  77. }
  78. /**
  79. * Get a sorted String[] of all paths to all files/dirs under dir.
  80. * Files with names starting with "." are ignored,
  81. * as are directory paths containing "CVS".
  82. * The directory prefix of the path is stripped.
  83. * Thus, given directory:
  84. * <pre>path/to
  85. * .cvsignore
  86. * CVS/
  87. * Root
  88. * Repository
  89. * Base.java
  90. * com/
  91. * parc/
  92. * messages.properties
  93. * org/
  94. * aspectj/
  95. * Version.java
  96. * </pre>
  97. * a call
  98. * <pre>
  99. * dirPaths(new File("path/to"), new String[0]);
  100. * </pre>
  101. * returns
  102. * <pre>
  103. * { "Base.java", "com/parc/messages.properties",
  104. * "org/aspectj/Version.java" }
  105. * </pre>
  106. * while the call
  107. * <pre>
  108. * dirPaths(new File("path/to"), new String[] { ".java"});
  109. * </pre>
  110. * returns
  111. * <pre>
  112. * { "Base.java", "org/aspectj/Version.java" }
  113. * </pre>
  114. * @param dir the File path to the directory to inspect
  115. * @param suffixes if not empty, require files returned to have this suffix
  116. * @return sorted String[] of all paths to all files under dir
  117. * ending with one of the listed suffixes
  118. * but not starting with "."
  119. */
  120. public static String[] dirPaths(File dir, String[] suffixes) {
  121. ArrayList result = new ArrayList();
  122. doDirPaths(dir, result);
  123. // if suffixes required, remove those without suffixes
  124. if (!LangUtil.isEmpty(suffixes)) {
  125. for (ListIterator iter = result.listIterator(); iter.hasNext();) {
  126. String path = iter.next().toString();
  127. boolean hasSuffix = false;
  128. for (int i = 0; !hasSuffix && (i < suffixes.length); i++) {
  129. hasSuffix = path.endsWith(suffixes[i]);
  130. }
  131. if (!hasSuffix) {
  132. iter.remove();
  133. }
  134. }
  135. }
  136. Collections.sort(result);
  137. // trim prefix
  138. final String prefix = dir.getPath();
  139. final int len = prefix.length() + 1; // plus directory separator
  140. String[] ra = (String[]) result.toArray(new String[0]);
  141. for (int i = 0; i < ra.length; i++) {
  142. // assertTrue(ra[i].startsWith(prefix));
  143. assertTrue(ra[i], ra[i].length() > len);
  144. ra[i] = ra[i].substring(len);
  145. }
  146. return ra;
  147. }
  148. /**
  149. * @param dir the File to read - ignored if null, not a directory,
  150. * or has "CVS" in its path
  151. * @param useSuffix if true, then use dir as suffix to path
  152. */
  153. private static void doDirPaths(File dir, ArrayList paths) {
  154. if ((null == dir) || !dir.canRead()
  155. || (-1 != dir.getPath().indexOf("CVS"))) {
  156. return;
  157. }
  158. File[] files = dir.listFiles();
  159. for (int i = 0; i < files.length; i++) {
  160. String path = files[i].getPath();
  161. if (!files[i].getName().startsWith(".")) {
  162. if (files[i].isFile()) {
  163. paths.add(path);
  164. } else if (files[i].isDirectory()) {
  165. doDirPaths(files[i], paths);
  166. } else {
  167. log("not file or dir: "
  168. + dir + "/" + path);
  169. }
  170. }
  171. }
  172. }
  173. /** Print s if logging is enabled */
  174. private static void log(String s) {
  175. if (log) {
  176. System.err.println(s);
  177. }
  178. }
  179. /** List of File files or directories to delete when exiting */
  180. final ArrayList tempFiles;
  181. public FileUtilTest(String s) {
  182. super(s);
  183. tempFiles = new ArrayList();
  184. }
  185. public void tearDown() {
  186. for (ListIterator iter = tempFiles.listIterator(); iter.hasNext();) {
  187. File dir = (File) iter.next();
  188. log("removing " + dir);
  189. FileUtil.deleteContents(dir);
  190. dir.delete();
  191. iter.remove();
  192. }
  193. }
  194. public void testNotIsFileIsDirectory() {
  195. File noSuchFile = new File("foo");
  196. assertTrue(!noSuchFile.isFile());
  197. assertTrue(!noSuchFile.isDirectory());
  198. }
  199. public void testGetBestFile() {
  200. assertNull(FileUtil.getBestFile((String[]) null));
  201. assertNull(FileUtil.getBestFile(new String[0]));
  202. assertNull(FileUtil.getBestFile(new String[] {"!"}));
  203. File f = FileUtil.getBestFile(new String[] {"."});
  204. assertNotNull(f);
  205. f = FileUtil.getBestFile(new String[] {"!", "."});
  206. assertNotNull(f);
  207. assertTrue(f.canRead());
  208. boolean setProperty = false;
  209. try {
  210. System.setProperty("bestfile", ".");
  211. setProperty = true;
  212. } catch (Throwable t) {
  213. // ignore Security, etc.
  214. }
  215. if (setProperty) {
  216. f = FileUtil.getBestFile(new String[] {"sp:bestfile"});
  217. assertNotNull(f);
  218. assertTrue(f.canRead());
  219. }
  220. }
  221. public void testCopyFiles() {
  222. // bad input
  223. Class iaxClass = IllegalArgumentException.class;
  224. checkCopyFiles(null, null, iaxClass, false);
  225. File noSuchFile = new File("foo");
  226. checkCopyFiles(noSuchFile, null, iaxClass, false);
  227. checkCopyFiles(noSuchFile, noSuchFile, iaxClass, false);
  228. File tempDir = FileUtil.getTempDir("testCopyFiles");
  229. tempFiles.add(tempDir);
  230. File fromFile = new File(tempDir, "fromFile");
  231. String err = FileUtil.writeAsString(fromFile, "contents of from file");
  232. assertTrue(err, null == err);
  233. checkCopyFiles(fromFile, null, iaxClass, false);
  234. checkCopyFiles(fromFile, fromFile, iaxClass, false);
  235. // file-file
  236. File toFile = new File(tempDir, "toFile");
  237. checkCopyFiles(fromFile, toFile, null, true);
  238. // file-dir
  239. File toDir= new File(tempDir, "toDir");
  240. assertTrue(toDir.mkdirs());
  241. checkCopyFiles(fromFile, toDir, null, true);
  242. // dir-dir
  243. File fromDir= new File(tempDir, "fromDir");
  244. assertTrue(fromDir.mkdirs());
  245. checkCopyFiles(fromFile, fromDir, null, false);
  246. File toFile2 = new File(fromDir, "toFile2");
  247. checkCopyFiles(fromFile, toFile2, null, false);
  248. checkCopyFiles(fromDir, toDir, null, true);
  249. }
  250. void checkCopyFiles(File from, File to, Class exceptionClass, boolean clean) {
  251. try {
  252. FileUtil.copyFile(from, to);
  253. assertTrue(null == exceptionClass);
  254. if (to.isFile()) {
  255. assertTrue(from.length() == to.length()); // XXX cheap test
  256. } else if (!from.isDirectory()){
  257. File toFile = new File(to, from.getName());
  258. assertTrue(from.length() == toFile.length());
  259. } else {
  260. // from is a dir and to is a dir, toDir should be created, and have the
  261. // same contents as fromDir.
  262. assertTrue(to.exists());
  263. assertTrue(from.listFiles().length == to.listFiles().length);
  264. }
  265. } catch (Throwable t) {
  266. assertTrue(null != exceptionClass);
  267. assertTrue(exceptionClass.isAssignableFrom(t.getClass()));
  268. } finally {
  269. if (clean && (null != to) && (to.exists())) {
  270. if (to.isDirectory()) {
  271. FileUtil.deleteContents(to);
  272. }
  273. to.delete();
  274. }
  275. }
  276. }
  277. public void testDirCopySubdirs() throws IOException {
  278. File srcDir = new File("src");
  279. File destDir = FileUtil.getTempDir("testDirCopySubdirs");
  280. tempFiles.add(destDir);
  281. FileUtil.copyDir(srcDir, destDir);
  282. assertSame("testDirCopySubdirs", dirPaths(srcDir), dirPaths(destDir));
  283. }
  284. public void testDirCopySubdirsSuffix() throws IOException {
  285. File srcDir = new File("src");
  286. File destDir = FileUtil.getTempDir("testDirCopySubdirsSuffix");
  287. tempFiles.add(destDir);
  288. FileUtil.copyDir(srcDir, destDir, ".java", ".aj");
  289. String[] sources = dirPaths(srcDir, new String[] { ".java" });
  290. for (int i = 0; i < sources.length; i++) {
  291. sources[i] = sources[i].substring(0, sources[i].length()-4);
  292. }
  293. String[] sinks = dirPaths(destDir, new String[] { ".aj" });
  294. for (int i = 0; i < sinks.length; i++) {
  295. sinks[i] = sinks[i].substring(0, sinks[i].length()-2);
  296. }
  297. assertSame("testDirCopySubdirs", sources, sinks);
  298. }
  299. public void testGetURL() {
  300. String[] args = new String[]
  301. {".", "../util/testdata", "../lib/test/aspectjrt.jar" };
  302. for (int i = 0; i < args.length; i++) {
  303. checkGetURL(args[i]);
  304. }
  305. }
  306. /**
  307. * Method checkGetURL.
  308. * @param string
  309. * @param uRL
  310. */
  311. private void checkGetURL(String arg) {
  312. assertTrue(null != arg);
  313. File f = new File(arg);
  314. assertTrue(null != f);
  315. URL url = FileUtil.getFileURL(f);
  316. assertTrue(null != url);
  317. log("url " + url);
  318. if (!f.exists()) {
  319. log("not exist " + f);
  320. } else if (f.isDirectory()) {
  321. log("directory " + f);
  322. } else {
  323. log(" file " + f);
  324. InputStream in = null;
  325. try {
  326. in = url.openStream();
  327. } catch (IOException e) {
  328. assertTrue("IOException: " + e, false);
  329. } finally {
  330. if (null != in) {
  331. try { in.close(); }
  332. catch (IOException e) {}
  333. }
  334. }
  335. }
  336. }
  337. public void testGetTempDir() {
  338. boolean pass = true;
  339. boolean delete = true;
  340. checkGetTempDir("parent", null, pass, delete);
  341. checkGetTempDir(null, "child", pass, delete);
  342. tempFiles.add(checkGetTempDir("parent", "child", pass, !delete).getParentFile());
  343. tempFiles.add(checkGetTempDir("parent", "child", pass, !delete).getParentFile());
  344. tempFiles.add(checkGetTempDir("parent", "child", pass, !delete).getParentFile());
  345. }
  346. File checkGetTempDir(String parent, String child, boolean ok, boolean delete) {
  347. File parentDir = FileUtil.getTempDir(parent);
  348. assertTrue("unable to create " + parent, null != parentDir);
  349. File dir = FileUtil.makeNewChildDir(parentDir, child);
  350. log("parent=" + parent + " child=" + child + " -> " + dir);
  351. assertTrue("dir: " + dir, ok == (dir.canWrite() && dir.isDirectory()));
  352. if (delete) {
  353. dir.delete();
  354. parentDir.delete();
  355. }
  356. return dir;
  357. }
  358. public void testRandomFileString() {
  359. ArrayList results = new ArrayList();
  360. for (int i = 0; i < 1000; i++) {
  361. String s = FileUtil.randomFileString();
  362. if (results.contains(s)) {
  363. log("warning: got duplicate at iteration " + i);
  364. }
  365. results.add(s);
  366. // System.err.print(" " + s);
  367. // if (0 == (i % 5)) {
  368. // System.err.println("");
  369. // }
  370. }
  371. }
  372. public void testNormalizedPath() {
  373. File tempFile = null;
  374. try {
  375. tempFile = File.createTempFile("FileUtilTest_testNormalizedPath", "tmp");
  376. tempFiles.add(tempFile);
  377. } catch (IOException e) {
  378. log("aborting test - unable to create temp file");
  379. return;
  380. }
  381. File parentDir = tempFile.getParentFile();
  382. String tempFilePath = FileUtil.normalizedPath(tempFile, parentDir);
  383. assertEquals(tempFile.getName(), tempFilePath);
  384. }
  385. public void testFileToClassName() {
  386. File basedir = new File("/base/dir"); // never created
  387. File classFile = new File(basedir, "foo/Bar.class");
  388. assertEquals("foo.Bar", FileUtil.fileToClassName(basedir, classFile));
  389. classFile = new File(basedir, "foo\\Bar.class");
  390. assertEquals("foo.Bar", FileUtil.fileToClassName(basedir, classFile));
  391. assertEquals("Bar", FileUtil.fileToClassName(null, classFile));
  392. classFile = new File("/home/classes/org/aspectj/lang/JoinPoint.class");
  393. assertEquals("org.aspectj.lang.JoinPoint", FileUtil.fileToClassName(null, classFile));
  394. classFile = new File("/home/classes/com/sun/tools/Javac.class");
  395. assertEquals("com.sun.tools.Javac", FileUtil.fileToClassName(null, classFile));
  396. }
  397. public void testDeleteContents() {
  398. File tempDir = FileUtil.getTempDir("testDeleteContents");
  399. tempFiles.add(tempDir);
  400. File f = new File(tempDir, "foo");
  401. f.mkdirs();
  402. File g = new File(f, "bar");
  403. g.mkdirs();
  404. File h = new File(g, "bash");
  405. h.mkdirs();
  406. int d = FileUtil.deleteContents(f);
  407. assertTrue(0 == d);
  408. assertTrue(0 == f.list().length);
  409. f.delete();
  410. assertTrue(!f.exists());
  411. }
  412. public void testLineSeek() {
  413. File tempDir = FileUtil.getTempDir("testLineSeek");
  414. tempFiles.add(tempDir);
  415. File file = new File(tempDir, "testLineSeek");
  416. String path = file.getPath();
  417. String contents = "0123456789" + LangUtil.EOL;
  418. contents += contents;
  419. FileUtil.writeAsString(file, contents);
  420. tempFiles.add(file);
  421. List sourceList = new ArrayList();
  422. sourceList.add(file.getPath());
  423. final ArrayList errors = new ArrayList();
  424. final PrintStream errorSink = new PrintStream(System.err, true) {
  425. public void println(String error) {
  426. errors.add(error);
  427. }
  428. };
  429. for (int i = 0; i < 10; i++) {
  430. List result = FileUtil.lineSeek(""+i, sourceList, true, errorSink);
  431. assertEquals(2, result.size());
  432. assertEquals(path + ":1:" + i, result.get(0));
  433. assertEquals(path + ":2:" + i, result.get(1));
  434. if (!LangUtil.isEmpty(errors)) { // XXX prefer fast-fail?
  435. assertTrue("errors: " + errors, false);
  436. }
  437. }
  438. }
  439. public void testLineSeekMore() {
  440. final int MAX = 3; // 1..10
  441. File tempDir = FileUtil.getTempDir("testLineSeekMore");
  442. tempFiles.add(tempDir);
  443. final String prefix = new File(tempDir, "testLineSeek").getPath();
  444. // setup files 0..MAX with 2*MAX lines
  445. String[] sources = new String[MAX];
  446. StringBuffer sb = new StringBuffer();
  447. for (int i = 0; i < sources.length; i++) {
  448. sources[i] = new File(prefix + i).getPath();
  449. sb.append("not matched");
  450. sb.append(LangUtil.EOL);
  451. sb.append("0123456789");
  452. sb.append(LangUtil.EOL);
  453. }
  454. final String contents = sb.toString();
  455. for (int i = 0; i < sources.length; i++) {
  456. File file = new File(sources[i]);
  457. FileUtil.writeAsString(file, contents);
  458. tempFiles.add(file);
  459. }
  460. // now test
  461. final ArrayList errors = new ArrayList();
  462. final PrintStream errorSink = new PrintStream(System.err, true) {
  463. public void println(String error) {
  464. errors.add(error);
  465. }
  466. };
  467. List sourceList = new ArrayList();
  468. sourceList.addAll(Arrays.asList(sources));
  469. sourceList = Collections.unmodifiableList(sourceList);
  470. for (int k = 0; k < sources.length; k++) {
  471. List result = FileUtil.lineSeek(""+k, sourceList, true, errorSink);
  472. // number k found in every other line of every file at index k
  473. Iterator iter = result.iterator();
  474. for (int i = 0; i < MAX; i++) { // for each file
  475. for (int j = 1; j < (MAX+1); j++) { // for every other line
  476. assertTrue(iter.hasNext());
  477. assertEquals(prefix + i + ":" + 2*j + ":" + k, iter.next());
  478. }
  479. }
  480. if (!LangUtil.isEmpty(errors)) { // XXX prefer fast-fail?
  481. assertTrue("errors: " + errors, false);
  482. }
  483. }
  484. }
  485. public void testDirCopyNoSubdirs() throws IOException {
  486. String[] srcFiles = new String[] { "one.java", "two.java", "three.java"};
  487. String[] destFiles = new String[] { "three.java", "four.java", "five.java" };
  488. String[] allFiles = new String[]
  489. { "one.java", "two.java", "three.java", "four.java", "five.java" };
  490. File srcDir = makeTempDir("FileUtilUT_srcDir", srcFiles);
  491. File destDir = makeTempDir("FileUtilUT_destDir", destFiles);
  492. assertTrue(null != srcDir);
  493. assertTrue(null != destDir);
  494. assertTrue(NONE == dirContains(srcDir, srcFiles));
  495. assertTrue(NONE == dirContains(destDir, destFiles));
  496. FileUtil.copyDir(srcDir, destDir);
  497. String[] resultOne = dirContains(destDir, allFiles);
  498. FileUtil.copyDir(srcDir, destDir);
  499. String[] resultTwo = dirContains(destDir, allFiles);
  500. assertTrue(NONE == resultOne);
  501. assertTrue(NONE == resultTwo);
  502. }
  503. public void testDirCopyNoSubdirsWithSuffixes() throws IOException {
  504. String[] srcFiles = new String[] { "one.java", "two.java", "three.java"};
  505. String[] destFiles = new String[] { "three.java", "four.java", "five.java" };
  506. String[] allFiles = new String[]
  507. { "one.aj", "two.aj", "three.aj", "three.java", "four.java", "five.java" };
  508. File srcDir = makeTempDir("FileUtilUT_srcDir", srcFiles);
  509. File destDir = makeTempDir("FileUtilUT_destDir", destFiles);
  510. assertTrue(null != srcDir);
  511. assertTrue(null != destDir);
  512. assertTrue(NONE == dirContains(srcDir, srcFiles));
  513. assertTrue(NONE == dirContains(destDir, destFiles));
  514. FileUtil.copyDir(srcDir, destDir, ".java", ".aj");
  515. FileUtil.copyDir(srcDir, destDir, ".java", ".aj");
  516. assertTrue(NONE == dirContains(destDir, allFiles));
  517. assertTrue(NONE == dirContains(destDir, allFiles));
  518. }
  519. public void testDirCopySubdirsSuffixRoundTrip() throws IOException {
  520. final File srcDir = new File("src");
  521. final File one = FileUtil.getTempDir("testDirCopySubdirsSuffixRoundTrip_1");
  522. final File two = FileUtil.getTempDir("testDirCopySubdirsSuffixRoundTrip_2");
  523. FileUtil.copyDir(srcDir, one); // no selection
  524. FileUtil.copyDir(two, one, ".java", ".aj"); // only .java files
  525. FileUtil.copyDir(one, two, ".aj", ".java");
  526. FileUtil.deleteContents(one);
  527. one.delete();
  528. FileUtil.deleteContents(two);
  529. two.delete();
  530. }
  531. /**
  532. * Create temp dir at loc containing temp files files.
  533. * Result is registered for deletion on cleanup.
  534. */
  535. File makeTempDir(String loc, String[] filenames) throws IOException {
  536. File d = new File(loc);
  537. d.mkdirs();
  538. assertTrue(d.exists());
  539. tempFiles.add(d);
  540. assertTrue(d.canWrite());
  541. for (int i = 0; i < filenames.length; i++) {
  542. File f = new File(d, filenames[i]);
  543. assertTrue(filenames[i], f.createNewFile());
  544. }
  545. return d;
  546. }
  547. public void testPipeEmpty() {
  548. checkPipe("");
  549. }
  550. public void testPipeMin() {
  551. checkPipe("0");
  552. }
  553. public void testPipe() {
  554. String str = "The quick brown fox jumped over the lazy dog";
  555. StringBuffer sb = new StringBuffer();
  556. for (int i = 0; i < 4096; i++) {
  557. sb.append(str);
  558. }
  559. checkPipe(sb.toString());
  560. }
  561. void checkPipe(String data) {
  562. StringBufferInputStream in = new StringBufferInputStream(data);
  563. ByteArrayOutputStream out = new ByteArrayOutputStream();
  564. FileUtil.Pipe pipe = new FileUtil.Pipe(in, out);
  565. pipe.run();
  566. assertTrue(data.equals(out.toString()));
  567. assertTrue(null == pipe.getThrown());
  568. assertEquals("totalWritten", data.length(), pipe.totalWritten());
  569. }
  570. public void testPipeThrown() {
  571. final String data = "The quick brown fox jumped over the lazy dog";
  572. final IOException thrown = new IOException("test");
  573. StringBufferInputStream in = new StringBufferInputStream(data);
  574. OutputStream out = new OutputStream() {
  575. public void write(int b) throws IOException {
  576. throw thrown;
  577. }
  578. };
  579. FileUtil.Pipe pipe = new FileUtil.Pipe(in, out);
  580. pipe.run();
  581. assertEquals("totalWritten", 0, pipe.totalWritten());
  582. assertTrue(thrown == pipe.getThrown());
  583. }
  584. public void xtestPipeHalt() { // this test periodically fails on the build machine -
  585. // disabling till we have time to figure out why
  586. final long MAX = 1000000;
  587. InputStream in = new InputStream() {
  588. long max = 0;
  589. public int read() throws IOException {
  590. if (max++ > MAX) {
  591. throw new IOException("test failed");
  592. }
  593. return 1;
  594. }
  595. };
  596. final int minWritten = 20;
  597. class Flag {
  598. boolean hit;
  599. }
  600. final Flag flag = new Flag();
  601. OutputStream out = new OutputStream() {
  602. long max = 0;
  603. public void write(int b) throws IOException {
  604. if (max++ > MAX) {
  605. throw new IOException("test failed");
  606. } else if (max > minWritten) {
  607. if (!flag.hit) {
  608. flag.hit = true;
  609. }
  610. }
  611. }
  612. };
  613. class Result {
  614. long totalWritten;
  615. Throwable thrown;
  616. boolean set;
  617. }
  618. final Result result = new Result();
  619. FileUtil.Pipe pipe = new FileUtil.Pipe(in, out) {
  620. protected void completing(
  621. long totalWritten,
  622. Throwable thrown) {
  623. result.totalWritten = totalWritten;
  624. result.thrown = thrown;
  625. result.set = true;
  626. }
  627. };
  628. // start it up
  629. new Thread(pipe).start();
  630. // wait for minWritten input
  631. while (!flag.hit) {
  632. try {
  633. Thread.sleep(5l);
  634. } catch (InterruptedException e) {
  635. // ignore
  636. }
  637. }
  638. // halt
  639. assertTrue(pipe.halt(true, true));
  640. assertTrue(result.set);
  641. assertTrue("Expected null but result.thrown = "+result.thrown,null == result.thrown);
  642. assertTrue(null == pipe.getThrown());
  643. assertEquals("total written", result.totalWritten, pipe.totalWritten());
  644. if (minWritten > pipe.totalWritten()) {
  645. assertTrue("written: " + pipe.totalWritten(), false);
  646. }
  647. }
  648. }