1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.maven.shared.utils.io;
20
21 import javax.annotation.Nonnull;
22
23 import java.io.BufferedOutputStream;
24 import java.io.File;
25 import java.io.FileInputStream;
26 import java.io.FileNotFoundException;
27 import java.io.FileOutputStream;
28 import java.io.FileReader;
29 import java.io.FileWriter;
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.OutputStream;
33 import java.io.Reader;
34 import java.io.Writer;
35 import java.net.URL;
36 import java.nio.file.Files;
37 import java.util.Arrays;
38 import java.util.HashMap;
39 import java.util.HashSet;
40 import java.util.List;
41 import java.util.Map;
42 import java.util.concurrent.TimeUnit;
43
44 import org.apache.commons.io.IOUtils;
45 import org.apache.maven.shared.utils.Os;
46 import org.apache.maven.shared.utils.testhelpers.FileTestHelper;
47 import org.codehaus.plexus.util.InterpolationFilterReader;
48 import org.hamcrest.CoreMatchers;
49 import org.junit.Before;
50 import org.junit.Ignore;
51 import org.junit.Rule;
52 import org.junit.Test;
53 import org.junit.rules.TemporaryFolder;
54 import org.junit.rules.TestName;
55
56 import static org.hamcrest.CoreMatchers.containsString;
57 import static org.hamcrest.CoreMatchers.hasItems;
58 import static org.hamcrest.CoreMatchers.is;
59 import static org.hamcrest.CoreMatchers.not;
60 import static org.hamcrest.MatcherAssert.assertThat;
61 import static org.junit.Assert.assertEquals;
62 import static org.junit.Assert.assertFalse;
63 import static org.junit.Assert.assertTrue;
64 import static org.junit.Assert.fail;
65 import static org.junit.Assume.assumeFalse;
66 import static org.junit.Assume.assumeThat;
67
68
69
70
71
72
73
74
75
76
77
78 @SuppressWarnings("deprecation")
79 public class FileUtilsTest {
80
81
82
83 @Rule
84 public TemporaryFolder tempFolder = new TemporaryFolder();
85
86 @Rule
87 public TestName name = new TestName();
88
89
90
91
92 private static final int TEST_DIRECTORY_SIZE = 0;
93
94 private File testFile1;
95
96 private File testFile2;
97
98 private long testFile1Size;
99
100 private long testFile2Size;
101
102
103
104
105 @Before
106 public void setUp() throws Exception {
107 testFile1 = tempFolder.newFile("file1-test.txt");
108 testFile2 = tempFolder.newFile("file1a-test.txt");
109
110 testFile1Size = (int) testFile1.length();
111 testFile2Size = (int) testFile2.length();
112
113 tempFolder.getRoot().mkdirs();
114 createFile(testFile1, testFile1Size);
115 createFile(testFile2, testFile2Size);
116 FileUtils.deleteDirectory(tempFolder.getRoot());
117 tempFolder.getRoot().mkdirs();
118 createFile(testFile1, testFile1Size);
119 createFile(testFile2, testFile2Size);
120 }
121
122 private static void createFile(File file, long size) throws IOException {
123 if (!file.getParentFile().exists()) {
124 throw new IOException("Cannot create file " + file + " as the parent directory does not exist");
125 }
126
127 try (OutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
128 FileTestHelper.generateTestData(out, size);
129 }
130 }
131
132
133
134
135 private void assertEqualContent(byte[] b0, File file) throws IOException {
136 int count = 0, numRead = 0;
137 byte[] b1 = new byte[b0.length];
138 try (InputStream is = new FileInputStream(file)) {
139 while (count < b0.length && numRead >= 0) {
140 numRead = is.read(b1, count, b0.length);
141 count += numRead;
142 }
143 assertThat("Different number of bytes: ", count, is(b0.length));
144 for (int i = 0; i < count; i++) {
145 assertEquals("byte " + i + " differs", b1[i], b0[i]);
146 }
147 }
148 }
149
150 private void deleteFile(File file) {
151 if (file.exists()) {
152 assertTrue("Couldn't delete file: " + file, file.delete());
153 }
154 }
155
156
157 @Test
158 public void toFile1() throws Exception {
159 URL url = new URL("file", null, "a/b/c/file.txt");
160 File file = FileUtils.toFile(url);
161 assertThat(file.toString(), containsString("file.txt"));
162 }
163
164 @Test
165 public void toFile2() throws Exception {
166 URL url = new URL("file", null, "a/b/c/file%20n%61me%2520.tx%74");
167 File file = FileUtils.toFile(url);
168 assertThat(file.toString(), containsString("file name%20.txt"));
169 }
170
171 @Test
172 public void toFile3() throws Exception {
173 assertThat(FileUtils.toFile(null), CoreMatchers.nullValue());
174 assertThat(FileUtils.toFile(new URL("http://jakarta.apache.org")), CoreMatchers.nullValue());
175 }
176
177 @Test(expected = NumberFormatException.class)
178 public void toFile4() throws Exception {
179 URL url = new URL("file", null, "a/b/c/file%%20%me.txt%");
180 File file = FileUtils.toFile(url);
181 assertThat(file.toString(), containsString("file% %me.txt%"));
182 }
183
184
185
186
187 @Test
188 public void toFile5() throws Exception {
189 URL url = new URL("file", null, "both%20are%20100%20%25%20true");
190 File file = FileUtils.toFile(url);
191 assertThat(file.toString(), is("both are 100 % true"));
192 }
193
194 @Test
195 public void toFileUtf8() throws Exception {
196 URL url = new URL("file", null, "/home/%C3%A4%C3%B6%C3%BC%C3%9F");
197 File file = FileUtils.toFile(url);
198 assertThat(file.toString(), not(containsString("\u00E4\u00F6\u00FC\u00DF")));
199 }
200
201
202
203 @Test
204 public void toURLs1() throws Exception {
205 File[] files = new File[] {
206 new File(tempFolder.getRoot(), "file1.txt"),
207 new File(tempFolder.getRoot(), "file2.txt"),
208 new File(tempFolder.getRoot(), "test file.txt"),
209 };
210 URL[] urls = FileUtils.toURLs(files);
211
212 assertThat(urls.length, is(files.length));
213 assertThat(urls[0].toExternalForm().startsWith("file:"), is(true));
214 assertThat(urls[0].toExternalForm().contains("file1.txt"), is(true));
215 assertThat(urls[1].toExternalForm().startsWith("file:"), is(true));
216 assertThat(urls[1].toExternalForm(), containsString("file2.txt"));
217
218
219 assertThat(urls[2].toExternalForm().startsWith("file:"), is(true));
220 assertThat(urls[2].toExternalForm(), containsString("test%20file.txt"));
221 }
222
223
224
225 @Test
226 public void contentEquals() throws Exception {
227
228 File file = new File(tempFolder.getRoot(), name.getMethodName());
229 File file2 = new File(tempFolder.getRoot(), name.getMethodName() + "2");
230
231 assertThat(FileUtils.contentEquals(file, file), is(true));
232 assertThat(FileUtils.contentEquals(file, file2), is(true));
233 assertThat(FileUtils.contentEquals(file2, file2), is(true));
234 assertThat(FileUtils.contentEquals(file2, file), is(true));
235
236
237 FileUtils.contentEquals(tempFolder.getRoot(), tempFolder.getRoot());
238
239
240 File objFile1 = new File(tempFolder.getRoot(), name.getMethodName() + ".object");
241 objFile1.deleteOnExit();
242 FileUtils.copyURLToFile(getClass().getResource("/java/lang/Object.class"), objFile1);
243
244 File objFile1b = new File(tempFolder.getRoot(), name.getMethodName() + ".object2");
245 objFile1.deleteOnExit();
246 FileUtils.copyURLToFile(getClass().getResource("/java/lang/Object.class"), objFile1b);
247
248 File objFile2 = new File(tempFolder.getRoot(), name.getMethodName() + ".collection");
249 objFile2.deleteOnExit();
250 FileUtils.copyURLToFile(getClass().getResource("/java/util/Collection.class"), objFile2);
251
252 assertThat(FileUtils.contentEquals(objFile1, objFile2), is(false));
253 assertThat(FileUtils.contentEquals(objFile1b, objFile2), is(false));
254 assertThat(FileUtils.contentEquals(objFile1, objFile1b), is(true));
255
256 assertThat(FileUtils.contentEquals(objFile1, objFile1), is(true));
257 assertThat(FileUtils.contentEquals(objFile1b, objFile1b), is(true));
258 assertThat(FileUtils.contentEquals(objFile2, objFile2), is(true));
259
260
261 file.createNewFile();
262 file2.createNewFile();
263 assertThat(FileUtils.contentEquals(file, file), is(true));
264 assertThat(FileUtils.contentEquals(file, file2), is(true));
265 }
266
267
268
269 @Test
270 public void copyURLToFile() throws Exception {
271
272 File file = new File(tempFolder.getRoot(), name.getMethodName());
273 file.deleteOnExit();
274
275
276 String resourceName = "/java/lang/Object.class";
277 FileUtils.copyURLToFile(getClass().getResource(resourceName), file);
278
279
280 try (FileInputStream fis = new FileInputStream(file)) {
281 assertThat(
282 "Content is not equal.",
283 IOUtil.contentEquals(getClass().getResourceAsStream(resourceName), fis),
284 is(true));
285 }
286
287 }
288
289
290
291 @Test
292 public void forceMkdir() throws Exception {
293
294 FileUtils.forceMkdir(tempFolder.getRoot());
295
296
297 File testFile = new File(tempFolder.getRoot(), name.getMethodName());
298 testFile.deleteOnExit();
299 testFile.createNewFile();
300 assertThat("Test file does not exist.", testFile.exists(), is(true));
301
302
303 try {
304 FileUtils.forceMkdir(testFile);
305 fail("Exception expected.");
306 } catch (IOException ex) {
307 }
308
309 testFile.delete();
310
311
312 FileUtils.forceMkdir(testFile);
313 assertThat("Directory was not created.", testFile.exists(), is(true));
314 }
315
316
317
318 @Test
319 public void sizeOfDirectory() throws Exception {
320 File file = new File(tempFolder.getRoot(), name.getMethodName());
321
322
323 try {
324 FileUtils.sizeOfDirectory(file);
325 fail("Exception expected.");
326 } catch (IllegalArgumentException ex) {
327 }
328
329
330 file.createNewFile();
331 file.deleteOnExit();
332
333
334 try {
335 FileUtils.sizeOfDirectory(file);
336 fail("Exception expected.");
337 } catch (IllegalArgumentException ex) {
338 }
339
340
341 file.delete();
342 file.mkdir();
343
344 assertThat("Unexpected directory size", FileUtils.sizeOfDirectory(file), is((long) TEST_DIRECTORY_SIZE));
345 }
346
347
348
349 @Test
350 public void copyFile1() throws Exception {
351 File destination = new File(tempFolder.getRoot(), "copy1.txt");
352
353
354
355
356
357 FileUtils.copyFile(testFile1, destination);
358 assertThat("Check Exist", destination.exists(), is(true));
359 assertThat("Check Full copy", destination.length(), is(testFile1Size));
360
361
362
363 }
364
365
366 private static long MODIFIED_TODAY =
367 (System.currentTimeMillis() / TimeUnit.MINUTES.toMillis(1)) * TimeUnit.MINUTES.toMillis(1);
368
369
370 private static long MODIFIED_YESTERDAY = MODIFIED_TODAY - TimeUnit.DAYS.toMillis(1);
371
372
373 private static long MODIFIED_LAST_WEEK = MODIFIED_TODAY - TimeUnit.DAYS.toMillis(7);
374
375 @Test
376 public void copyFileWithNoFiltersAndNoDestination() throws Exception {
377 File from = write("from.txt", MODIFIED_YESTERDAY, "Hello World!");
378 File to = new File(tempFolder.getRoot(), "to.txt");
379
380 FileUtils.copyFile(from, to, null, (FileUtils.FilterWrapper[]) null);
381
382 assertTrue("to.txt did not exist so should have been written", to.lastModified() >= MODIFIED_TODAY);
383 assertFileContent(to, "Hello World!");
384 }
385
386 @Test
387 public void copyFileWithNoFiltersAndLastModifiedDateOfZeroAndNoDestination() throws Exception {
388 File from = write("from.txt", MODIFIED_YESTERDAY, "Hello World!");
389 File to = new File(tempFolder.getRoot(), "to.txt");
390
391 from.setLastModified(0);
392 FileUtils.copyFile(from, to, null, (FileUtils.FilterWrapper[]) null);
393
394 assertTrue("to.txt did not exist so should have been written", to.lastModified() >= MODIFIED_TODAY);
395 assertFileContent(to, "Hello World!");
396 }
397
398 @Test
399 public void copyFileWithNoFiltersAndOutdatedDestination() throws Exception {
400 File from = write("from.txt", MODIFIED_YESTERDAY, "Hello World!");
401 File to = write("to.txt", MODIFIED_LAST_WEEK, "Older content");
402
403 FileUtils.copyFile(from, to, null, (FileUtils.FilterWrapper[]) null);
404
405 assertTrue("to.txt was outdated so should have been overwritten", to.lastModified() >= MODIFIED_TODAY);
406 assertFileContent(to, "Hello World!");
407 }
408
409 @Test
410 public void copyFileWithNoFiltersAndNewerDestination() throws Exception {
411 File from = write("from.txt", MODIFIED_LAST_WEEK, "Hello World!");
412 File to = write("to.txt", MODIFIED_YESTERDAY, "Older content");
413
414 FileUtils.copyFile(from, to, null, (FileUtils.FilterWrapper[]) null);
415
416 assertTrue("to.txt was newer so should have been left alone", to.lastModified() < MODIFIED_TODAY);
417 assertFileContent(to, "Older content");
418 }
419
420 @Test
421 public void copyFileWithNoFiltersAndNewerDestinationButForcedOverwrite() throws Exception {
422 File from = write("from.txt", MODIFIED_LAST_WEEK, "Hello World!");
423 File to = write("to.txt", MODIFIED_YESTERDAY, "Older content");
424
425 FileUtils.copyFile(from, to, null, null, true);
426
427 assertTrue("to.txt was newer but the overwrite should have been forced", to.lastModified() >= MODIFIED_TODAY);
428 assertFileContent(to, "Hello World!");
429 }
430
431 @Test
432 public void copyFileWithFilteringButNoFilters() throws Exception {
433 File from = write("from.txt", MODIFIED_YESTERDAY, "Hello ${name}!");
434 File to = write("to.txt", MODIFIED_LAST_WEEK, "Older content");
435
436 FileUtils.copyFile(from, to, null);
437
438 assertTrue("to.txt was outdated so should have been overwritten", to.lastModified() >= MODIFIED_TODAY);
439 assertFileContent(to, "Hello ${name}!");
440 }
441
442 @Test
443 public void copyFileWithFilteringAndNoDestination() throws Exception {
444 File from = write("from.txt", MODIFIED_YESTERDAY, "Hello ${name}!");
445 File to = new File(tempFolder.getRoot(), "to.txt");
446
447 FileUtils.copyFile(from, to, null, wrappers("name", "Bob"));
448
449 assertTrue("to.txt did not exist so should have been written", to.lastModified() >= MODIFIED_TODAY);
450 assertFileContent(to, "Hello Bob!");
451 }
452
453 @Test
454 public void copyFileWithFilteringAndOutdatedDestination() throws Exception {
455 File from = write("from.txt", MODIFIED_YESTERDAY, "Hello ${name}!");
456 File to = write("to.txt", MODIFIED_LAST_WEEK, "Older content");
457
458 FileUtils.copyFile(from, to, null, wrappers("name", "Bob"));
459
460 assertTrue("to.txt was outdated so should have been overwritten", to.lastModified() >= MODIFIED_TODAY);
461 assertFileContent(to, "Hello Bob!");
462 }
463
464 @Test
465 public void copyFileWithFilteringAndNewerDestinationButForcedOverwrite() throws Exception {
466 File from = write("from.txt", MODIFIED_LAST_WEEK, "Hello ${name}!");
467 File to = write("to.txt", MODIFIED_YESTERDAY, "Older content");
468
469 FileUtils.copyFile(from, to, null, wrappers("name", "Bob"), true);
470
471 assertTrue("to.txt was newer but the overwrite should have been forced", to.lastModified() >= MODIFIED_TODAY);
472 assertFileContent(to, "Hello Bob!");
473 }
474
475 @Test
476 public void copyFileWithFilteringAndNewerDestinationButModifiedContent() throws Exception {
477 File from = write("from.txt", MODIFIED_LAST_WEEK, "Hello ${name}!");
478 File to = write("to.txt", MODIFIED_YESTERDAY, "Hello Charlie!");
479
480 FileUtils.copyFile(from, to, null, wrappers("name", "Bob"));
481
482 assertTrue("to.txt was outdated so should have been overwritten", to.lastModified() >= MODIFIED_TODAY);
483 assertFileContent(to, "Hello Bob!");
484 }
485
486 @Test
487 public void copyFileWithFilteringAndNewerDestinationAndMatchingContent() throws Exception {
488 File from = write("from.txt", MODIFIED_LAST_WEEK, "Hello ${name}!");
489 File to = write("to.txt", MODIFIED_YESTERDAY, "Hello Bob!");
490
491 FileUtils.copyFile(from, to, null, wrappers("name", "Bob"));
492
493 assertFileContent(to, "Hello Bob!");
494 assertTrue("to.txt content should be unchanged and have been left alone", to.lastModified() < MODIFIED_TODAY);
495 }
496
497 private static FileUtils.FilterWrapper[] wrappers(String key, String value) {
498 final Map<String, Object> map = new HashMap<>();
499 map.put(key, value);
500 return new FileUtils.FilterWrapper[] {
501 new FileUtils.FilterWrapper() {
502 @Override
503 public Reader getReader(Reader reader) {
504 return new InterpolationFilterReader(reader, map);
505 }
506 }
507 };
508 }
509
510 private File write(@Nonnull String name, long lastModified, @Nonnull String text) throws IOException {
511 final File file = new File(tempFolder.getRoot(), name);
512 try (final Writer writer = new FileWriter(file)) {
513 writer.write(text);
514 }
515 assertTrue(file.setLastModified(lastModified));
516 assertEquals("Failed to set lastModified date on " + file.getPath(), lastModified, file.lastModified());
517 return file;
518 }
519
520 private static void assertFileContent(@Nonnull File file, @Nonnull String expected) throws IOException {
521 try (Reader in = new FileReader(file)) {
522 assertEquals("Expected " + file.getPath() + " to contain: " + expected, expected, IOUtils.toString(in));
523 }
524 }
525
526 @Test
527 public void copyFileThatIsSymlink() throws Exception {
528 assumeFalse(Os.isFamily(Os.FAMILY_WINDOWS));
529
530 File destination = new File(tempFolder.getRoot(), "symCopy.txt");
531
532 File testDir = SymlinkTestSetup.createStandardSymlinkTestDir(new File("target/test/symlinkCopy"));
533
534 FileUtils.copyFile(new File(testDir, "symR"), destination);
535
536 assertTrue(Files.isSymbolicLink(destination.toPath()));
537 }
538
539 @Test
540 public void deleteFile() throws Exception {
541 File destination = new File(tempFolder.getRoot(), "copy1.txt");
542 FileUtils.copyFile(testFile1, destination);
543 FileUtils.delete(destination);
544 assertThat("Check Exist", destination.exists(), is(false));
545 }
546
547 @Test(expected = IOException.class)
548 public void deleteFileNofile() throws Exception {
549 File destination = new File("abc/cde");
550 FileUtils.delete(destination);
551 }
552
553 @Test
554 public void deleteFileLegacy() throws Exception {
555 File destination = new File(tempFolder.getRoot(), "copy1.txt");
556 FileUtils.copyFile(testFile1, destination);
557 assertTrue(FileUtils.deleteLegacyStyle(destination));
558 }
559
560 @Test
561 public void deleteFileLegacyNofile() throws Exception {
562 File destination = new File("abc/cde");
563 assertFalse(FileUtils.deleteLegacyStyle(destination));
564 }
565
566 @Test
567 public void copyFileWithPermissions() throws Exception {
568 File source = new File("src/test/resources/executable");
569 source.setExecutable(true);
570 assumeThat("Need an existing file to copy", source.exists(), is(true));
571 assumeThat("Need an executable file to copy", source.canExecute(), is(true));
572
573 File destination = new File(tempFolder.getRoot(), "executable-copy");
574
575 FileUtils.copyFile(source, destination);
576
577 assertThat(
578 "destination not exists: " + destination.getAbsolutePath() + ", directory content: "
579 + Arrays.asList(destination.getParentFile().list()),
580 Files.exists(destination.toPath()),
581 is(true));
582
583 assertThat("Check copy executable", destination.canExecute(), is(true));
584 }
585
586 @Test
587 public void copyFile2() throws Exception {
588 File destination = new File(tempFolder.getRoot(), "copy2.txt");
589
590
591
592
593
594 FileUtils.copyFile(testFile1, destination);
595 assertThat("Check Exist", destination.exists(), is(true));
596 assertThat("Check Full copy", destination.length(), is(testFile2Size));
597
598
599
600 }
601
602 @Test
603 public void copyToSelf() throws IOException {
604 File destination = new File(tempFolder.getRoot(), "copy3.txt");
605
606 FileUtils.copyFile(testFile1, destination);
607
608 FileUtils.copyFile(destination, destination);
609 }
610
611 @Test
612 public void copyDirectoryToNonExistingDest() throws Exception {
613 createFile(testFile1, 1234);
614 createFile(testFile2, 4321);
615 File srcDir = tempFolder.getRoot();
616 File subDir = new File(srcDir, "sub");
617 subDir.mkdir();
618 File subFile = new File(subDir, "A.txt");
619 FileUtils.fileWrite(subFile, "UTF8", "HELLO WORLD");
620 File destDir = new File(System.getProperty("java.io.tmpdir"), "tmp-FileUtilsTestCase");
621 FileUtils.deleteDirectory(destDir);
622
623 FileUtils.copyDirectory(srcDir, destDir);
624
625 assertTrue(destDir.exists());
626 assertEquals(FileUtils.sizeOfDirectory(destDir), FileUtils.sizeOfDirectory(srcDir));
627 assertTrue(new File(destDir, "sub/A.txt").exists());
628 FileUtils.deleteDirectory(destDir);
629 }
630
631 @Test
632 public void copyDirectoryToExistingDest() throws IOException {
633 createFile(testFile1, 1234);
634 createFile(testFile2, 4321);
635 File srcDir = tempFolder.getRoot();
636 File subDir = new File(srcDir, "sub");
637 assertTrue(subDir.mkdir());
638 File subFile = new File(subDir, "A.txt");
639 FileUtils.fileWrite(subFile, "UTF8", "HELLO WORLD");
640 File destDir = new File(System.getProperty("java.io.tmpdir"), "tmp-FileUtilsTestCase");
641 FileUtils.deleteDirectory(destDir);
642 assertTrue(destDir.mkdirs());
643
644 FileUtils.copyDirectory(srcDir, destDir);
645
646 assertEquals(FileUtils.sizeOfDirectory(destDir), FileUtils.sizeOfDirectory(srcDir));
647 assertTrue(new File(destDir, "sub/A.txt").exists());
648 }
649
650 @Test
651 public void copyDirectoryErrors_nullDestination() throws IOException {
652 try {
653 FileUtils.copyDirectory(new File("a"), null);
654 fail();
655 } catch (NullPointerException ex) {
656 }
657 }
658
659 @Test
660 public void copyDirectoryErrors_copyToSelf() {
661 try {
662 FileUtils.copyDirectory(tempFolder.getRoot(), tempFolder.getRoot());
663 fail();
664 } catch (IOException ex) {
665 }
666 }
667
668 @Test
669 public void copyDirectoryErrors() throws IOException {
670 try {
671 FileUtils.copyDirectory(null, null);
672 fail();
673 } catch (NullPointerException ex) {
674 }
675 try {
676 FileUtils.copyDirectory(null, new File("a"));
677 fail();
678 } catch (NullPointerException ex) {
679 }
680 try {
681 FileUtils.copyDirectory(tempFolder.getRoot(), testFile1);
682 fail();
683 } catch (IOException ex) {
684 }
685 }
686
687
688
689 @Test
690 public void forceDeleteAFile1() throws Exception {
691 File destination = new File(tempFolder.getRoot(), "copy1.txt");
692 destination.createNewFile();
693 assertTrue("Copy1.txt doesn't exist to delete", destination.exists());
694 FileUtils.forceDelete(destination);
695 assertFalse(destination.exists());
696 }
697
698 @Test
699 public void forceDeleteAFile2() throws Exception {
700 File destination = new File(tempFolder.getRoot(), "copy2.txt");
701 destination.createNewFile();
702 assertThat("Copy2.txt doesn't exist to delete", destination.exists(), is(true));
703 FileUtils.forceDelete(destination);
704 assertThat("Check No Exist", !destination.exists(), is(true));
705 }
706
707 @Test
708 @Ignore("Commons test case that is failing for plexus")
709 public void forceDeleteAFile3() throws Exception {
710 File destination = new File(tempFolder.getRoot(), "no_such_file");
711 assertThat("Check No Exist", !destination.exists(), is(true));
712 try {
713 FileUtils.forceDelete(destination);
714 fail("Should generate FileNotFoundException");
715 } catch (FileNotFoundException ignored) {
716 }
717 }
718
719
720
721 @Test
722 @Ignore("Commons test case that is failing for plexus")
723 public void copyFile1ToDir() throws Exception {
724 File directory = new File(tempFolder.getRoot(), "subdir");
725 if (!directory.exists()) {
726 directory.mkdirs();
727 }
728 File destination = new File(directory, testFile1.getName());
729
730
731
732
733
734 FileUtils.copyFileToDirectory(testFile1, directory);
735 assertThat("Check Exist", destination.exists(), is(true));
736 assertThat("Check Full copy", destination.length(), is(testFile1Size));
737
738
739
740
741 try {
742 FileUtils.copyFileToDirectory(destination, directory);
743 fail("Should not be able to copy a file into the same directory as itself");
744 } catch (IOException ioe) {
745
746 }
747 }
748
749 @Test
750 public void copyFile2ToDir() throws Exception {
751 File directory = new File(tempFolder.getRoot(), "subdir");
752 if (!directory.exists()) {
753 directory.mkdirs();
754 }
755 File destination = new File(directory, testFile1.getName());
756
757
758
759
760
761 FileUtils.copyFileToDirectory(testFile1, directory);
762 assertThat("Check Exist", destination.exists(), is(true));
763 assertThat("Check Full copy", destination.length(), is(testFile2Size));
764
765
766
767 }
768
769
770
771 @Test
772 public void forceDeleteDir() throws Exception {
773 File testDirectory = tempFolder.newFolder(name.getMethodName());
774 FileUtils.forceDelete(testDirectory.getParentFile());
775 assertThat("Check No Exist", !testDirectory.getParentFile().exists(), is(true));
776 }
777
778
779
780
781 @Test
782 public void fileUtils() throws Exception {
783
784 File file1 = new File(tempFolder.getRoot(), "test.txt");
785 String filename = file1.getAbsolutePath();
786
787
788 try (OutputStream out = new java.io.FileOutputStream(file1)) {
789 out.write("This is a test".getBytes("UTF-8"));
790 }
791
792 File file2 = new File(tempFolder.getRoot(), "test2.txt");
793
794 FileUtils.fileWrite(file2, "UTF-8", filename);
795 assertThat(file2.exists(), is(true));
796 assertThat(file2.length() > 0, is(true));
797
798 String file2contents = FileUtils.fileRead(file2, "UTF-8");
799 assertThat("Second file's contents correct", filename.equals(file2contents), is(true));
800
801 assertThat(file2.delete(), is(true));
802
803 String contents = FileUtils.fileRead(new File(filename), "UTF-8");
804 assertThat("FileUtils.fileRead()", contents.equals("This is a test"), is(true));
805 }
806
807 @Test
808 public void fileReadWithDefaultEncoding() throws Exception {
809 File file = new File(tempFolder.getRoot(), "read.obj");
810 FileOutputStream out = new FileOutputStream(file);
811 byte[] text = "Hello /u1234".getBytes();
812 out.write(text);
813 out.close();
814
815 String data = FileUtils.fileRead(file);
816 assertThat(data, is("Hello /u1234"));
817 }
818
819 @Test
820 public void fileReadWithEncoding() throws Exception {
821 File file = new File(tempFolder.getRoot(), "read.obj");
822 FileOutputStream out = new FileOutputStream(file);
823 byte[] text = "Hello /u1234".getBytes("UTF8");
824 out.write(text);
825 out.close();
826
827 String data = FileUtils.fileRead(file, "UTF8");
828 assertThat(data, is("Hello /u1234"));
829 }
830
831 @Test
832 @Ignore("Commons test case that is failing for plexus")
833 public void readLines() throws Exception {
834 File file = FileTestHelper.newFile(tempFolder, "lines.txt");
835 try {
836 String[] data = new String[] {"hello", "/u1234", "", "this is", "some text"};
837 FileTestHelper.createLineBasedFile(file, data);
838
839 List<String> lines = FileUtils.loadFile(file);
840 assertThat(lines, is(Arrays.asList(data)));
841 } finally {
842 deleteFile(file);
843 }
844 }
845
846 @Test
847 public void writeStringToFile1() throws Exception {
848 File file = new File(tempFolder.getRoot(), "write.txt");
849 FileUtils.fileWrite(file, "UTF8", "Hello /u1234");
850 byte[] text = "Hello /u1234".getBytes("UTF8");
851 assertEqualContent(text, file);
852 }
853
854 @Test
855 public void writeStringToFile2() throws Exception {
856 File file = new File(tempFolder.getRoot(), "write.txt");
857 FileUtils.fileWrite(file, null, "Hello /u1234");
858 byte[] text = "Hello /u1234".getBytes();
859 assertEqualContent(text, file);
860 }
861
862 @Test
863 public void writeCharSequence1() throws Exception {
864 File file = new File(tempFolder.getRoot(), "write.txt");
865 FileUtils.fileWrite(file, "UTF8", "Hello /u1234");
866 byte[] text = "Hello /u1234".getBytes("UTF8");
867 assertEqualContent(text, file);
868 }
869
870 @Test
871 public void writeCharSequence2() throws Exception {
872 File file = new File(tempFolder.getRoot(), "write.txt");
873 FileUtils.fileWrite(file, null, "Hello /u1234");
874 byte[] text = "Hello /u1234".getBytes();
875 assertEqualContent(text, file);
876 }
877
878 @Test
879 public void writeStringToFileWithEncoding_WithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception {
880 File file = FileTestHelper.newFile(tempFolder, "lines.txt");
881 FileUtils.fileWrite(file, null, "This line was there before you...");
882
883 FileUtils.fileAppend(file.getAbsolutePath(), "this is brand new data");
884
885 String expected = "This line was there before you..." + "this is brand new data";
886 String actual = FileUtils.fileRead(file);
887 assertThat(actual, is(expected));
888 }
889
890 @Test
891 public void writeStringToFile_WithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception {
892 File file = FileTestHelper.newFile(tempFolder, "lines.txt");
893 FileUtils.fileWrite(file, null, "This line was there before you...");
894
895 FileUtils.fileAppend(file.getAbsolutePath(), "this is brand new data");
896
897 String expected = "This line was there before you..." + "this is brand new data";
898 String actual = FileUtils.fileRead(file);
899 assertThat(actual, is(expected));
900 }
901
902 @Test
903 public void writeStringArrayToFile() throws Exception {
904 File file = new File(tempFolder.getRoot(), "writeArray.txt");
905 FileUtils.fileWriteArray(file, new String[] {"line1", "line2", "line3"});
906
907 byte[] text = "line1\nline2\nline3".getBytes("UTF8");
908 assertEqualContent(text, file);
909 }
910
911 @Test
912 public void writeStringArrayToFileWithEncoding() throws Exception {
913 File file = new File(tempFolder.getRoot(), "writeArray.txt");
914 FileUtils.fileWriteArray(file, "UTF8", new String[] {"line1", "line2", "line3"});
915
916 byte[] text = "line1\nline2\nline3".getBytes("UTF8");
917 assertEqualContent(text, file);
918 }
919
920 @Test
921 public void writeWithEncoding_WithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception {
922 File file = FileTestHelper.newFile(tempFolder, "lines.txt");
923 FileUtils.fileWrite(file, "UTF-8", "This line was there before you...");
924
925 FileUtils.fileAppend(file.getAbsolutePath(), "UTF-8", "this is brand new data");
926
927 String expected = "This line was there before you..." + "this is brand new data";
928 String actual = FileUtils.fileRead(file);
929 assertThat(actual, is(expected));
930 }
931
932 @Test
933 public void write_WithAppendOptionTrue_ShouldNotDeletePreviousFileLines() throws Exception {
934 File file = FileTestHelper.newFile(tempFolder, "lines.txt");
935 FileUtils.fileWrite(file, null, "This line was there before you...");
936
937 FileUtils.fileAppend(file.getAbsolutePath(), "this is brand new data");
938
939 String expected = "This line was there before you..." + "this is brand new data";
940 String actual = FileUtils.fileRead(file);
941 assertThat(actual, is(expected));
942 }
943
944 @Test(expected = NullPointerException.class)
945 public void blowUpOnNull() throws IOException {
946 FileUtils.deleteDirectory((File) null);
947 }
948
949 @Test
950 public void deleteQuietlyDir() throws IOException {
951 File testDirectory = new File(tempFolder.getRoot(), "testDeleteQuietlyDir");
952 File testFile = new File(testDirectory, "testDeleteQuietlyFile");
953 testDirectory.mkdirs();
954 createFile(testFile, 0);
955
956 assertThat(testDirectory.exists(), is(true));
957 assertThat(testFile.exists(), is(true));
958 FileUtils.deleteDirectory(testDirectory);
959 assertThat("Check No Exist", testDirectory.exists(), is(false));
960 assertThat("Check No Exist", testFile.exists(), is(false));
961 }
962
963 @Test
964 public void deleteQuietlyFile() throws IOException {
965 File testFile = new File(tempFolder.getRoot(), "testDeleteQuietlyFile");
966 createFile(testFile, 0);
967
968 assertThat(testFile.exists(), is(true));
969 FileUtils.deleteDirectory(testFile);
970 assertThat("Check No Exist", testFile.exists(), is(false));
971 }
972
973 @Test
974 public void deleteQuietlyNonExistent() throws IOException {
975 File testFile = new File(tempFolder.getRoot(), "testDeleteQuietlyNonExistent");
976 assertThat(testFile.exists(), is(false));
977
978 FileUtils.deleteDirectory(testFile);
979 }
980
981
982
983 @Test
984 public void getDefaultExcludes() throws Exception {
985 assertThat(Arrays.asList(FileUtils.getDefaultExcludes()), hasItems(MINIMUM_DEFAULT_EXCLUDES));
986 }
987
988
989
990 @Test
991 public void getDefaultExcludesAsList() throws Exception {
992 assertThat(FileUtils.getDefaultExcludesAsList(), hasItems(MINIMUM_DEFAULT_EXCLUDES));
993 }
994
995
996
997 @Test
998 public void getDefaultExcludesAsString() throws Exception {
999 assertThat(
1000 new HashSet<String>(
1001 Arrays.asList(FileUtils.getDefaultExcludesAsString().split(","))),
1002 hasItems(MINIMUM_DEFAULT_EXCLUDES));
1003 }
1004
1005
1006
1007 @SuppressWarnings("ConstantConditions")
1008 @Test(expected = NullPointerException.class)
1009 public void nlowUpOnDirnameNull() throws Exception {
1010 FileUtils.dirname(null);
1011 }
1012
1013 @Test
1014 public void dirnameEmpty() throws Exception {
1015 assertThat(FileUtils.dirname(""), is(""));
1016 }
1017
1018 @Test
1019 public void dirnameFilename() throws Exception {
1020 assertThat(FileUtils.dirname("foo.bar.txt"), is(""));
1021 }
1022
1023 @Test
1024
1025 public void dirnameWindowsRootPathOnUnix() throws Exception {
1026 assumeThat(File.separatorChar, is('/'));
1027 assertThat(FileUtils.dirname("C:\\foo.bar.txt"), is(""));
1028 }
1029
1030 @Test
1031
1032 public void dirnameWindowsNonRootPathOnUnix() throws Exception {
1033 assumeThat(File.separatorChar, is('/'));
1034 assertThat(FileUtils.dirname("C:\\test\\foo.bar.txt"), is(""));
1035 }
1036
1037 @Test
1038
1039 public void dirnameUnixRootPathOnWindows() throws Exception {
1040 assumeThat(File.separatorChar, is('\\'));
1041 assertThat(FileUtils.dirname("/foo.bar.txt"), is(""));
1042 }
1043
1044 @Test
1045
1046 public void dirnameUnixNonRootPathOnWindows() throws Exception {
1047 assumeThat(File.separatorChar, is('\\'));
1048 assertThat(FileUtils.dirname("/test/foo.bar.txt"), is(""));
1049 }
1050
1051 @Test
1052 public void dirnameWindowsRootPathOnWindows() throws Exception {
1053 assumeThat(File.separatorChar, is('\\'));
1054 assertThat(FileUtils.dirname("C:\\foo.bar.txt"), is("C:"));
1055 }
1056
1057 @Test
1058 public void dirnameWindowsNonRootPathOnWindows() throws Exception {
1059 assumeThat(File.separatorChar, is('\\'));
1060 assertThat(FileUtils.dirname("C:\\test\\foo.bar.txt"), is("C:\\test"));
1061 }
1062
1063 @Test
1064 public void dirnameUnixRootPathOnUnix() throws Exception {
1065 assumeThat(File.separatorChar, is('/'));
1066 assertThat(FileUtils.dirname("/foo.bar.txt"), is(""));
1067 }
1068
1069 @Test
1070 public void dirnameUnixNonRootPathOnUnix() throws Exception {
1071 assumeThat(File.separatorChar, is('/'));
1072 assertThat(FileUtils.dirname("/test/foo.bar.txt"), is("/test"));
1073 }
1074
1075
1076
1077 @SuppressWarnings("ConstantConditions")
1078 @Test(expected = NullPointerException.class)
1079 public void blowUpOnFilenameNull() throws Exception {
1080 FileUtils.filename(null);
1081 }
1082
1083 @Test
1084 public void filenameEmpty() throws Exception {
1085 assertThat(FileUtils.filename(""), is(""));
1086 }
1087
1088 @Test
1089 public void filenameFilename() throws Exception {
1090 assertThat(FileUtils.filename("foo.bar.txt"), is("foo.bar.txt"));
1091 }
1092
1093 @Test
1094
1095 public void filenameWindowsRootPathOnUnix() throws Exception {
1096 assumeThat(File.separatorChar, is('/'));
1097 assertThat(FileUtils.filename("C:\\foo.bar.txt"), is("C:\\foo.bar.txt"));
1098 }
1099
1100 @Test
1101
1102 public void filenameWindowsNonRootPathOnUnix() throws Exception {
1103 assumeThat(File.separatorChar, is('/'));
1104 assertThat(FileUtils.filename("C:\\test\\foo.bar.txt"), is("C:\\test\\foo.bar.txt"));
1105 }
1106
1107 @Test
1108
1109 public void filenameUnixRootPathOnWindows() throws Exception {
1110 assumeThat(File.separatorChar, is('\\'));
1111 assertThat(FileUtils.filename("/foo.bar.txt"), is("/foo.bar.txt"));
1112 }
1113
1114 @Test
1115
1116 public void filenameUnixNonRootPathOnWindows() throws Exception {
1117 assumeThat(File.separatorChar, is('\\'));
1118 assertThat(FileUtils.filename("/test/foo.bar.txt"), is("/test/foo.bar.txt"));
1119 }
1120
1121 @Test
1122 public void filenameWindowsRootPathOnWindows() throws Exception {
1123 assumeThat(File.separatorChar, is('\\'));
1124 assertThat(FileUtils.filename("C:\\foo.bar.txt"), is("foo.bar.txt"));
1125 }
1126
1127 @Test
1128 public void filenameWindowsNonRootPathOnWindows() throws Exception {
1129 assumeThat(File.separatorChar, is('\\'));
1130 assertThat(FileUtils.filename("C:\\test\\foo.bar.txt"), is("foo.bar.txt"));
1131 }
1132
1133 @Test
1134 public void filenameUnixRootPathOnUnix() throws Exception {
1135 assumeThat(File.separatorChar, is('/'));
1136 assertThat(FileUtils.filename("/foo.bar.txt"), is("foo.bar.txt"));
1137 }
1138
1139 @Test
1140 public void filenameUnixNonRootPathOnUnix() throws Exception {
1141 assumeThat(File.separatorChar, is('/'));
1142 assertThat(FileUtils.filename("/test/foo.bar.txt"), is("foo.bar.txt"));
1143 }
1144
1145
1146
1147 @SuppressWarnings("ConstantConditions")
1148 @Test(expected = NullPointerException.class)
1149 public void blowUpOnNullExtension() throws Exception {
1150 FileUtils.extension(null);
1151 }
1152
1153 @Test
1154 public void extensionEmpty() throws Exception {
1155 assertThat(FileUtils.extension(""), is(""));
1156 }
1157
1158 @Test
1159 public void extensionFileName() throws Exception {
1160 assertThat(FileUtils.extension("foo.bar.txt"), is("txt"));
1161 }
1162
1163 @Test
1164 public void extensionFileNameNoExtension() throws Exception {
1165 assertThat(FileUtils.extension("foo_bar_txt"), is(""));
1166 }
1167
1168 @Test
1169
1170 public void extensionWindowsRootPathOnUnix() throws Exception {
1171 assumeThat(File.separatorChar, is('/'));
1172 assertThat(FileUtils.extension("C:\\foo.bar.txt"), is("txt"));
1173 }
1174
1175 @Test
1176
1177 public void extensionWindowsNonRootPathOnUnix() throws Exception {
1178 assumeThat(File.separatorChar, is('/'));
1179 assertThat(FileUtils.extension("C:\\test\\foo.bar.txt"), is("txt"));
1180 }
1181
1182 @Test
1183
1184 public void extensionUnixRootPathOnWindows() throws Exception {
1185 assumeThat(File.separatorChar, is('\\'));
1186 assertThat(FileUtils.extension("/foo.bar.txt"), is("txt"));
1187 }
1188
1189 @Test
1190
1191 public void extensionUnixNonRootPathOnWindows() throws Exception {
1192 assumeThat(File.separatorChar, is('\\'));
1193 assertThat(FileUtils.extension("/test/foo.bar.txt"), is("txt"));
1194 }
1195
1196 @Test
1197 public void extensionWindowsRootPathOnWindows() throws Exception {
1198 assumeThat(File.separatorChar, is('\\'));
1199 assertThat(FileUtils.extension("C:\\foo.bar.txt"), is("txt"));
1200 }
1201
1202 @Test
1203 public void extensionWindowsNonRootPathOnWindows() throws Exception {
1204 assumeThat(File.separatorChar, is('\\'));
1205 assertThat(FileUtils.extension("C:\\test\\foo.bar.txt"), is("txt"));
1206 }
1207
1208 @Test
1209 @Ignore("Wait until we can run with assembly 2.5 which will support symlinks properly")
1210 public void isASymbolicLink() throws IOException {
1211
1212 assumeFalse(Os.isFamily(Os.FAMILY_WINDOWS));
1213
1214 File file = new File("src/test/resources/symlinks/src/symDir");
1215 assertTrue(FileUtils.isSymbolicLink(file));
1216 }
1217
1218 @Test
1219 @Ignore("Wait until we can run with assembly 2.5 which will support symlinks properly")
1220 public void notASymbolicLink() throws IOException {
1221 File file = new File("src/test/resources/symlinks/src/");
1222 assertFalse(FileUtils.isSymbolicLink(file));
1223 }
1224
1225 @Test
1226 public void extensionUnixRootPathOnUnix() throws Exception {
1227 assumeThat(File.separatorChar, is('/'));
1228 assertThat(FileUtils.extension("/foo.bar.txt"), is("txt"));
1229 }
1230
1231 @Test
1232 public void extensionUnixNonRootPathOnUnix() throws Exception {
1233 assumeThat(File.separatorChar, is('/'));
1234 assertThat(FileUtils.extension("/test/foo.bar.txt"), is("txt"));
1235 }
1236
1237 @Test
1238 public void createAndReadSymlink() throws Exception {
1239 assumeFalse(Os.isFamily(Os.FAMILY_WINDOWS));
1240
1241 File file = new File("target/fzz");
1242 FileUtils.createSymbolicLink(file, new File("../target"));
1243
1244 final File file1 = Files.readSymbolicLink(file.toPath()).toFile();
1245 assertEquals("target", file1.getName());
1246 Files.delete(file.toPath());
1247 }
1248
1249 @Test
1250 public void createSymbolicLinkWithDifferentTargetOverwritesSymlink() throws Exception {
1251 assumeFalse(Os.isFamily(Os.FAMILY_WINDOWS));
1252
1253
1254
1255 final File symlink1 = new File(tempFolder.getRoot(), "symlink");
1256
1257 FileUtils.createSymbolicLink(symlink1, testFile1);
1258
1259
1260
1261 final File symlink2 = FileUtils.createSymbolicLink(symlink1, testFile2);
1262
1263
1264
1265 assertThat(Files.readSymbolicLink(symlink2.toPath()).toFile(), CoreMatchers.equalTo(testFile2));
1266 }
1267
1268
1269
1270 private static final String[] MINIMUM_DEFAULT_EXCLUDES = {
1271
1272 "**/*~",
1273 "**/#*#",
1274 "**/.#*",
1275 "**/%*%",
1276 "**/._*",
1277
1278
1279 "**/CVS",
1280 "**/CVS/**",
1281 "**/.cvsignore",
1282
1283
1284 "**/.svn",
1285 "**/.svn/**",
1286
1287
1288 "**/.arch-ids",
1289 "**/.arch-ids/**",
1290
1291
1292 "**/.bzr",
1293 "**/.bzr/**",
1294
1295
1296 "**/.MySCMServerInfo",
1297
1298
1299 "**/.DS_Store",
1300
1301
1302 "**/.metadata",
1303 "**/.metadata/**",
1304
1305
1306 "**/.hg",
1307 "**/.hg/**",
1308
1309
1310 "**/.git",
1311 "**/.git/**",
1312
1313
1314 "**/BitKeeper",
1315 "**/BitKeeper/**",
1316 "**/ChangeSet",
1317 "**/ChangeSet/**",
1318
1319
1320 "**/_darcs",
1321 "**/_darcs/**",
1322 "**/.darcsrepo",
1323 "**/.darcsrepo/**",
1324 "**/-darcs-backup*",
1325 "**/.darcs-temp-mail"
1326 };
1327 }