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 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  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. @SuppressWarnings("deprecation")
  36. public class FileUtilTest extends TestCase {
  37. public static final String[] NONE = new String[0];
  38. public static boolean log = false;
  39. public static void main(String[] args) {
  40. TestRunner.main(new String[] { "org.aspectj.util.FileUtilTest" });
  41. }
  42. public static void assertSame(String prefix, String[] lhs, String[] rhs) { // XXX cheap diff
  43. String srcPaths = LangUtil.arrayAsList(lhs).toString();
  44. String destPaths = LangUtil.arrayAsList(rhs).toString();
  45. if (!srcPaths.equals(destPaths)) {
  46. log("expected: " + srcPaths);
  47. log(" actual: " + destPaths);
  48. assertTrue(prefix + " expected=" + srcPaths + " != actual=" + destPaths, false);
  49. }
  50. }
  51. /**
  52. * Verify that dir contains files with names, and return the names of other files in dir.
  53. *
  54. * @return the contents of dir after excluding files or NONE if none
  55. * @throws AssertionFailedError if any names are not in dir
  56. */
  57. public static String[] dirContains(File dir, final String[] filenames) {
  58. final ArrayList<String> sought = new ArrayList<>(LangUtil.arrayAsList(filenames));
  59. FilenameFilter filter = new FilenameFilter() {
  60. public boolean accept(File d, String name) {
  61. return !sought.remove(name);
  62. }
  63. };
  64. // remove any found from sought and return remainder
  65. String[] found = dir.list(filter);
  66. if (0 < sought.size()) {
  67. assertTrue("found " + LangUtil.arrayAsList(dir.list()).toString() + " expected " + sought, false);
  68. }
  69. return (found.length == 0 ? NONE : found);
  70. }
  71. /** @return sorted String[] of all paths to all files/dirs under dir */
  72. public static String[] dirPaths(File dir) {
  73. return dirPaths(dir, new String[0]);
  74. }
  75. /**
  76. * Get a sorted String[] of all paths to all files/dirs under dir. Files with names starting with "." are ignored, as are
  77. * directory paths containing "CVS". The directory prefix of the path is stripped. Thus, given directory:
  78. *
  79. * <pre>
  80. * path/to
  81. * .cvsignore
  82. * CVS/
  83. * Root
  84. * Repository
  85. * Base.java
  86. * com/
  87. * parc/
  88. * messages.properties
  89. * org/
  90. * aspectj/
  91. * Version.java
  92. * </pre>
  93. *
  94. * a call
  95. *
  96. * <pre>
  97. * dirPaths(new File(&quot;path/to&quot;), new String[0]);
  98. * </pre>
  99. *
  100. * returns
  101. *
  102. * <pre>
  103. * { &quot;Base.java&quot;, &quot;com/parc/messages.properties&quot;, &quot;org/aspectj/Version.java&quot; }
  104. * </pre>
  105. *
  106. * while the call
  107. *
  108. * <pre>
  109. * dirPaths(new File(&quot;path/to&quot;), new String[] { &quot;.java&quot; });
  110. * </pre>
  111. *
  112. * returns
  113. *
  114. * <pre>
  115. * { &quot;Base.java&quot;, &quot;org/aspectj/Version.java&quot; }
  116. * </pre>
  117. *
  118. * @param dir the File path to the directory to inspect
  119. * @param suffixes if not empty, require files returned to have this suffix
  120. * @return sorted String[] of all paths to all files under dir ending with one of the listed suffixes but not starting with "."
  121. */
  122. public static String[] dirPaths(File dir, String[] suffixes) {
  123. ArrayList<String> result = new ArrayList<String>();
  124. doDirPaths(dir, result);
  125. // if suffixes required, remove those without suffixes
  126. if (!LangUtil.isEmpty(suffixes)) {
  127. for (ListIterator<String> iter = result.listIterator(); iter.hasNext();) {
  128. String path = iter.next().toString();
  129. boolean hasSuffix = false;
  130. for (int i = 0; !hasSuffix && (i < suffixes.length); i++) {
  131. hasSuffix = path.endsWith(suffixes[i]);
  132. }
  133. if (!hasSuffix) {
  134. iter.remove();
  135. }
  136. }
  137. }
  138. Collections.sort(result);
  139. // trim prefix
  140. final String prefix = dir.getPath();
  141. final int len = prefix.length() + 1; // plus directory separator
  142. String[] ra = result.toArray(new String[0]);
  143. for (int i = 0; i < ra.length; i++) {
  144. // assertTrue(ra[i].startsWith(prefix));
  145. assertTrue(ra[i], ra[i].length() > len);
  146. ra[i] = ra[i].substring(len);
  147. }
  148. return ra;
  149. }
  150. /**
  151. * @param dir the File to read - ignored if null, not a directory, or has "CVS" in its path
  152. * @param useSuffix if true, then use dir as suffix to path
  153. */
  154. private static void doDirPaths(File dir, ArrayList<String> paths) {
  155. if ((null == dir) || !dir.canRead() || (dir.getPath().contains("CVS"))) {
  156. return;
  157. }
  158. File[] files = dir.listFiles();
  159. for (File file : files) {
  160. String path = file.getPath();
  161. if (!file.getName().startsWith(".")) {
  162. if (file.isFile()) {
  163. paths.add(path);
  164. } else if (file.isDirectory()) {
  165. doDirPaths(file, paths);
  166. } else {
  167. log("not file or dir: " + dir + "/" + path);
  168. }
  169. }
  170. }
  171. }
  172. /** Print s if logging is enabled */
  173. private static void log(String s) {
  174. if (log) {
  175. System.err.println(s);
  176. }
  177. }
  178. /** List of File files or directories to delete when exiting */
  179. final ArrayList<File> tempFiles;
  180. public FileUtilTest(String s) {
  181. super(s);
  182. tempFiles = new ArrayList<File>();
  183. }
  184. public void tearDown() {
  185. for (ListIterator<File> iter = tempFiles.listIterator(); iter.hasNext();) {
  186. File dir = iter.next();
  187. log("removing " + dir);
  188. FileUtil.deleteContents(dir);
  189. dir.delete();
  190. iter.remove();
  191. }
  192. }
  193. public void testNotIsFileIsDirectory() {
  194. File noSuchFile = new File("foo");
  195. assertTrue(!noSuchFile.isFile());
  196. assertTrue(!noSuchFile.isDirectory());
  197. }
  198. public void testGetBestFile() {
  199. assertNull(FileUtil.getBestFile((String[]) null));
  200. assertNull(FileUtil.getBestFile(new String[0]));
  201. assertNull(FileUtil.getBestFile(new String[] { "!" }));
  202. File f = FileUtil.getBestFile(new String[] { "." });
  203. assertNotNull(f);
  204. f = FileUtil.getBestFile(new String[] { "!", "." });
  205. assertNotNull(f);
  206. assertTrue(f.canRead());
  207. boolean setProperty = false;
  208. try {
  209. System.setProperty("bestfile", ".");
  210. setProperty = true;
  211. } catch (Throwable t) {
  212. // ignore Security, etc.
  213. }
  214. if (setProperty) {
  215. f = FileUtil.getBestFile(new String[] { "sp:bestfile" });
  216. assertNotNull(f);
  217. assertTrue(f.canRead());
  218. }
  219. }
  220. public void testCopyFiles() {
  221. // bad input
  222. Class<?> iaxClass = IllegalArgumentException.class;
  223. checkCopyFiles(null, null, iaxClass, false);
  224. File noSuchFile = new File("foo");
  225. checkCopyFiles(noSuchFile, null, iaxClass, false);
  226. checkCopyFiles(noSuchFile, noSuchFile, iaxClass, false);
  227. File tempDir = FileUtil.getTempDir("testCopyFiles");
  228. tempFiles.add(tempDir);
  229. File fromFile = new File(tempDir, "fromFile");
  230. String err = FileUtil.writeAsString(fromFile, "contents of from file");
  231. assertTrue(err, null == err);
  232. checkCopyFiles(fromFile, null, iaxClass, false);
  233. checkCopyFiles(fromFile, fromFile, iaxClass, false);
  234. // file-file
  235. File toFile = new File(tempDir, "toFile");
  236. checkCopyFiles(fromFile, toFile, null, true);
  237. // file-dir
  238. File toDir = new File(tempDir, "toDir");
  239. assertTrue(toDir.mkdirs());
  240. checkCopyFiles(fromFile, toDir, null, true);
  241. // dir-dir
  242. File fromDir = new File(tempDir, "fromDir");
  243. assertTrue(fromDir.mkdirs());
  244. checkCopyFiles(fromFile, fromDir, null, false);
  245. File toFile2 = new File(fromDir, "toFile2");
  246. checkCopyFiles(fromFile, toFile2, null, false);
  247. checkCopyFiles(fromDir, toDir, null, true);
  248. }
  249. void checkCopyFiles(File from, File to, Class exceptionClass, boolean clean) {
  250. try {
  251. FileUtil.copyFile(from, to);
  252. assertTrue(null == exceptionClass);
  253. if (to.isFile()) {
  254. assertTrue(from.length() == to.length()); // XXX cheap test
  255. } else if (!from.isDirectory()) {
  256. File toFile = new File(to, from.getName());
  257. assertTrue(from.length() == toFile.length());
  258. } else {
  259. // from is a dir and to is a dir, toDir should be created, and have the
  260. // same contents as fromDir.
  261. assertTrue(to.exists());
  262. assertTrue(from.listFiles().length == to.listFiles().length);
  263. }
  264. } catch (Throwable t) {
  265. assertTrue(null != exceptionClass);
  266. assertTrue(exceptionClass.isAssignableFrom(t.getClass()));
  267. } finally {
  268. if (clean && (null != to) && (to.exists())) {
  269. if (to.isDirectory()) {
  270. FileUtil.deleteContents(to);
  271. }
  272. to.delete();
  273. }
  274. }
  275. }
  276. public void testDirCopySubdirs() throws IOException {
  277. File srcDir = new File("src");
  278. File destDir = FileUtil.getTempDir("testDirCopySubdirs");
  279. tempFiles.add(destDir);
  280. FileUtil.copyDir(srcDir, destDir);
  281. assertSame("testDirCopySubdirs", dirPaths(srcDir), dirPaths(destDir));
  282. }
  283. public void testDirCopySubdirsSuffix() throws IOException {
  284. File srcDir = new File("src");
  285. File destDir = FileUtil.getTempDir("testDirCopySubdirsSuffix");
  286. tempFiles.add(destDir);
  287. FileUtil.copyDir(srcDir, destDir, ".java", ".aj");
  288. String[] sources = dirPaths(srcDir, new String[] { ".java" });
  289. for (int i = 0; i < sources.length; i++) {
  290. sources[i] = sources[i].substring(0, sources[i].length() - 4);
  291. }
  292. String[] sinks = dirPaths(destDir, new String[] { ".aj" });
  293. for (int i = 0; i < sinks.length; i++) {
  294. sinks[i] = sinks[i].substring(0, sinks[i].length() - 2);
  295. }
  296. assertSame("testDirCopySubdirs", sources, sinks);
  297. }
  298. public void testGetURL() {
  299. String[] args = new String[] { ".", "../util/testdata", "../lib/test/aspectjrt.jar" };
  300. for (String arg : args) {
  301. checkGetURL(arg);
  302. }
  303. }
  304. /**
  305. * Method checkGetURL.
  306. *
  307. * @param string
  308. * @param uRL
  309. */
  310. private void checkGetURL(String arg) {
  311. assertTrue(null != arg);
  312. File f = new File(arg);
  313. URL url = FileUtil.getFileURL(f);
  314. assertTrue(null != url);
  315. log("url " + url);
  316. if (!f.exists()) {
  317. log("not exist " + f);
  318. } else if (f.isDirectory()) {
  319. log("directory " + f);
  320. } else {
  321. log(" file " + f);
  322. InputStream in = null;
  323. try {
  324. in = url.openStream();
  325. } catch (IOException e) {
  326. assertTrue("IOException: " + e, false);
  327. } finally {
  328. if (null != in) {
  329. try {
  330. in.close();
  331. } catch (IOException e) {
  332. }
  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<String> 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<String> sourceList = new ArrayList<String>();
  422. sourceList.add(file.getPath());
  423. final ArrayList<String> errors = new ArrayList<String>();
  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<String> 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 (String source : sources) {
  456. File file = new File(source);
  457. FileUtil.writeAsString(file, contents);
  458. tempFiles.add(file);
  459. }
  460. // now test
  461. final ArrayList<String> 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<String> 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<String> result = FileUtil.lineSeek("" + k, sourceList, true, errorSink);
  472. // number k found in every other line of every file at index k
  473. Iterator<String> 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[] { "one.java", "two.java", "three.java", "four.java", "five.java" };
  489. File srcDir = makeTempDir("FileUtilUT_srcDir", srcFiles);
  490. File destDir = makeTempDir("FileUtilUT_destDir", destFiles);
  491. assertTrue(null != srcDir);
  492. assertTrue(null != destDir);
  493. assertTrue(NONE == dirContains(srcDir, srcFiles));
  494. assertTrue(NONE == dirContains(destDir, destFiles));
  495. FileUtil.copyDir(srcDir, destDir);
  496. String[] resultOne = dirContains(destDir, allFiles);
  497. FileUtil.copyDir(srcDir, destDir);
  498. String[] resultTwo = dirContains(destDir, allFiles);
  499. assertTrue(NONE == resultOne);
  500. assertTrue(NONE == resultTwo);
  501. }
  502. public void testDirCopyNoSubdirsWithSuffixes() throws IOException {
  503. String[] srcFiles = new String[] { "one.java", "two.java", "three.java" };
  504. String[] destFiles = new String[] { "three.java", "four.java", "five.java" };
  505. String[] allFiles = new String[] { "one.aj", "two.aj", "three.aj", "three.java", "four.java", "five.java" };
  506. File srcDir = makeTempDir("FileUtilUT_srcDir", srcFiles);
  507. File destDir = makeTempDir("FileUtilUT_destDir", destFiles);
  508. assertTrue(null != srcDir);
  509. assertTrue(null != destDir);
  510. assertTrue(NONE == dirContains(srcDir, srcFiles));
  511. assertTrue(NONE == dirContains(destDir, destFiles));
  512. FileUtil.copyDir(srcDir, destDir, ".java", ".aj");
  513. FileUtil.copyDir(srcDir, destDir, ".java", ".aj");
  514. assertTrue(NONE == dirContains(destDir, allFiles));
  515. assertTrue(NONE == dirContains(destDir, allFiles));
  516. }
  517. public void testDirCopySubdirsSuffixRoundTrip() throws IOException {
  518. final File srcDir = new File("src");
  519. final File one = FileUtil.getTempDir("testDirCopySubdirsSuffixRoundTrip_1");
  520. final File two = FileUtil.getTempDir("testDirCopySubdirsSuffixRoundTrip_2");
  521. FileUtil.copyDir(srcDir, one); // no selection
  522. FileUtil.copyDir(two, one, ".java", ".aj"); // only .java files
  523. FileUtil.copyDir(one, two, ".aj", ".java");
  524. FileUtil.deleteContents(one);
  525. one.delete();
  526. FileUtil.deleteContents(two);
  527. two.delete();
  528. }
  529. /**
  530. * Create temp dir at loc containing temp files files. Result is registered for deletion on cleanup.
  531. */
  532. File makeTempDir(String loc, String[] filenames) throws IOException {
  533. File d = new File(loc);
  534. d.mkdirs();
  535. assertTrue(d.exists());
  536. tempFiles.add(d);
  537. assertTrue(d.canWrite());
  538. for (String filename : filenames) {
  539. File f = new File(d, filename);
  540. assertTrue(filename, f.createNewFile());
  541. }
  542. return d;
  543. }
  544. public void testPipeEmpty() {
  545. checkPipe("");
  546. }
  547. public void testPipeMin() {
  548. checkPipe("0");
  549. }
  550. public void testPipe() {
  551. String str = "The quick brown fox jumped over the lazy dog";
  552. StringBuffer sb = new StringBuffer();
  553. for (int i = 0; i < 4096; i++) {
  554. sb.append(str);
  555. }
  556. checkPipe(sb.toString());
  557. }
  558. void checkPipe(String data) {
  559. StringBufferInputStream in = new StringBufferInputStream(data);
  560. ByteArrayOutputStream out = new ByteArrayOutputStream();
  561. FileUtil.Pipe pipe = new FileUtil.Pipe(in, out, 100l, true, true);
  562. pipe.run();
  563. assertTrue(data.equals(out.toString()));
  564. assertTrue(null == pipe.getThrown());
  565. assertEquals("totalWritten", data.length(), pipe.totalWritten());
  566. }
  567. public void testPipeThrown() {
  568. final String data = "The quick brown fox jumped over the lazy dog";
  569. final IOException thrown = new IOException("test");
  570. StringBufferInputStream in = new StringBufferInputStream(data);
  571. OutputStream out = new OutputStream() {
  572. public void write(int b) throws IOException {
  573. throw thrown;
  574. }
  575. };
  576. FileUtil.Pipe pipe = new FileUtil.Pipe(in, out, 100l, true, true);
  577. pipe.run();
  578. assertEquals("totalWritten", 0, pipe.totalWritten());
  579. assertTrue(thrown == pipe.getThrown());
  580. }
  581. public void xtestPipeHalt() { // this test periodically fails on the build machine -
  582. // disabling till we have time to figure out why
  583. final long MAX = 1000000;
  584. InputStream in = new InputStream() {
  585. long max = 0;
  586. public int read() throws IOException {
  587. if (max++ > MAX) {
  588. throw new IOException("test failed");
  589. }
  590. return 1;
  591. }
  592. };
  593. final int minWritten = 20;
  594. class Flag {
  595. boolean hit;
  596. }
  597. final Flag flag = new Flag();
  598. OutputStream out = new OutputStream() {
  599. long max = 0;
  600. public void write(int b) throws IOException {
  601. if (max++ > MAX) {
  602. throw new IOException("test failed");
  603. } else if (max > minWritten) {
  604. if (!flag.hit) {
  605. flag.hit = true;
  606. }
  607. }
  608. }
  609. };
  610. class Result {
  611. long totalWritten;
  612. Throwable thrown;
  613. boolean set;
  614. }
  615. final Result result = new Result();
  616. FileUtil.Pipe pipe = new FileUtil.Pipe(in, out, 100l, true, true) {
  617. protected void completing(long totalWritten, Throwable thrown) {
  618. result.totalWritten = totalWritten;
  619. result.thrown = thrown;
  620. result.set = true;
  621. }
  622. };
  623. // start it up
  624. new Thread(pipe).start();
  625. // wait for minWritten input
  626. while (!flag.hit) {
  627. try {
  628. Thread.sleep(5l);
  629. } catch (InterruptedException e) {
  630. // ignore
  631. }
  632. }
  633. // halt
  634. assertTrue(pipe.halt(true, true));
  635. assertTrue(result.set);
  636. assertTrue("Expected null but result.thrown = " + result.thrown, null == result.thrown);
  637. assertTrue(null == pipe.getThrown());
  638. assertEquals("total written", result.totalWritten, pipe.totalWritten());
  639. if (minWritten > pipe.totalWritten()) {
  640. assertTrue("written: " + pipe.totalWritten(), false);
  641. }
  642. }
  643. }