KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > edu > rice > cs > util > FileOpsTest


1 /*BEGIN_COPYRIGHT_BLOCK
2  *
3  * This file is part of DrJava. Download the current version of this project from http://www.drjava.org/
4  * or http://sourceforge.net/projects/drjava/
5  *
6  * DrJava Open Source License
7  *
8  * Copyright (C) 2001-2005 JavaPLT group at Rice University (javaplt@rice.edu). All rights reserved.
9  *
10  * Developed by: Java Programming Languages Team, Rice University, http://www.cs.rice.edu/~javaplt/
11  *
12  * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
13  * documentation files (the "Software"), to deal with the Software without restriction, including without limitation
14  * the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
15  * to permit persons to whom the Software is furnished to do so, subject to the following conditions:
16  *
17  * - Redistributions of source code must retain the above copyright notice, this list of conditions and the
18  * following disclaimers.
19  * - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
20  * following disclaimers in the documentation and/or other materials provided with the distribution.
21  * - Neither the names of DrJava, the JavaPLT, Rice University, nor the names of its contributors may be used to
22  * endorse or promote products derived from this Software without specific prior written permission.
23  * - Products derived from this software may not be called "DrJava" nor use the term "DrJava" as part of their
24  * names without prior written permission from the JavaPLT group. For permission, write to javaplt@rice.edu.
25  *
26  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
27  * THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28  * CONTRIBUTORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
29  * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
30  * WITH THE SOFTWARE.
31  *
32  *END_COPYRIGHT_BLOCK*/

33
34 package edu.rice.cs.util;
35
36 import junit.framework.*;
37 import java.io.*;
38
39 import java.util.Arrays JavaDoc;
40 import java.util.ArrayList JavaDoc;
41 import java.util.LinkedList JavaDoc;
42 import java.util.List JavaDoc;
43 import java.util.Set JavaDoc;
44 import java.util.TreeSet JavaDoc;
45
46 import edu.rice.cs.drjava.config.FileOption;
47 import edu.rice.cs.drjava.DrJavaTestCase;
48 import edu.rice.cs.util.newjvm.ExecJVM;
49 import edu.rice.cs.util.FileOps;
50
51 /** Test cases for {@link FileOps}.
52  * @version $Id: FileOpsTest.java 4069 2007-01-18 17:11:59Z dlsmith $
53  */

54 @SuppressWarnings JavaDoc("deprecation") public class FileOpsTest extends DrJavaTestCase {
55   private static final Log _log = new Log("FileOpsTest.txt", false);
56   public static final String JavaDoc TEXT = "hi, dude.";
57   public static final String JavaDoc PREFIX = "prefix";
58   public static final String JavaDoc SUFFIX = ".suffix";
59
60   public void testCreateTempDirectory() throws IOException {
61     File dir = FileOps.createTempDirectory(PREFIX);
62     try {
63       assertTrue("createTempDirectory result is a directory", dir.isDirectory());
64       assertTrue("temp directory has correct prefix", dir.getName().startsWith(PREFIX));
65     }
66     finally { assertTrue("delete directory", dir.delete()); }
67   }
68
69   public void testReadAndWriteTempFile() throws IOException {
70     File file = FileOps.writeStringToNewTempFile(PREFIX, SUFFIX, TEXT);
71     try {
72       assertTrue("temp file has correct prefix",
73                  file.getName().startsWith(PREFIX));
74       assertTrue("temp file has correct suffix",
75                  file.getName().endsWith(SUFFIX));
76
77       String JavaDoc read = FileOps.readFileAsString(file);
78       assertEquals("contents after read", TEXT, read);
79     }
80     finally {
81       assertTrue("delete file", file.delete());
82     }
83   }
84
85   public void testRecursiveDirectoryDelete() throws IOException {
86     final File baseDir = FileOps.createTempDirectory(PREFIX);
87
88     File parentDir = baseDir;
89     boolean ret;
90
91     // create a bunch of subdirs and some files.
92
for (int i = 0; i < 5; i++) {
93       File subdir = new File(parentDir, "subdir" + i);
94       ret = subdir.mkdir();
95       assertTrue("create directory " + subdir, ret);
96
97       for (int j = 0; j < 2; j++) {
98         File file = new File(parentDir, "file" + i + "-" + j);
99         FileOps.writeStringToFile(file,
100                                   "Some text for file "+file.getAbsolutePath());
101         assertTrue(file + " exists", file.exists());
102       }
103
104       parentDir = subdir;
105     }
106
107     // OK, now try to delete base.
108
ret = FileOps.deleteDirectory(baseDir);
109     assertTrue("delete directory result", ret);
110     assertEquals("directory exists after deleting it", false, baseDir.exists());
111   }
112
113
114   /**
115    * This method checks that backups are made correctly, that when a save fails,
116    * no data is lost, and that when a save is attempted on a write-protected file,
117    * the save fails (bug #782963).
118    */

119   public void testSaveFile() throws IOException {
120     File writeTo = File.createTempFile("fileops", ".test").getCanonicalFile();
121     writeTo.deleteOnExit();
122     File backup = new File(writeTo.getPath() + "~");
123
124     FileOps.saveFile(new FileOps.DefaultFileSaver(writeTo) {
125       public void saveTo(OutputStream os) throws IOException {
126         String JavaDoc output = "version 1";
127         os.write(output.getBytes());
128       }
129       public boolean shouldBackup() {
130         return false;
131       }
132     });
133     assertEquals("save w/o backup", "version 1", FileOps.readFileAsString(writeTo));
134     assertEquals("save w/o backup did not backup", false, backup.exists());
135
136     FileOps.saveFile(new FileOps.DefaultFileSaver(writeTo) {
137       public void saveTo(OutputStream os) throws IOException {
138         String JavaDoc output = "version 2";
139         os.write(output.getBytes());
140       }
141     });
142     assertEquals("save2 w backup", "version 2", FileOps.readFileAsString(writeTo));
143     assertEquals("save2 w backup did backup", "version 1",
144                  FileOps.readFileAsString(backup));
145
146     FileOps.saveFile(new FileOps.DefaultFileSaver(writeTo) {
147       public void saveTo(OutputStream os) throws IOException {
148         String JavaDoc output = "version 3";
149         os.write(output.getBytes());
150       }
151     });
152     assertEquals("save3 w backup on", "version 3", FileOps.readFileAsString(writeTo));
153     assertEquals("save3 w backup on did not backup", "version 1",
154                  FileOps.readFileAsString(backup));
155
156
157     /* Now see what happens when saving fails and we were not making a backup. Nothing should change. */
158     try {
159       FileOps.saveFile(new FileOps.DefaultFileSaver(writeTo) {
160         public void saveTo(OutputStream os) throws IOException {
161           String JavaDoc output = "version 4";
162           os.write(output.getBytes());
163           throw new IOException();
164         }
165       });
166       fail("IOException not propagated");
167     }
168     catch (IOException ioe){ }//do nothing, this is expected
169
assertEquals("failed save4 w/o backup", "version 3",
170                  FileOps.readFileAsString(writeTo));
171     assertEquals("failed save4 w/o backup check original backup", "version 1",
172                  FileOps.readFileAsString(backup));
173
174     /* Now see what happens when saving fails and we were making a backup */
175     try {
176       FileOps.saveFile(new FileOps.DefaultFileSaver(writeTo) {
177         public boolean shouldBackup () {
178           return true;
179         }
180         public void saveTo(OutputStream os) throws IOException {
181           String JavaDoc output = "version 5";
182           os.write(output.getBytes());
183           throw new IOException();
184         }
185       });
186       fail("IOException not propagated spot 2");
187     }
188     catch(IOException ioe){ } //do nothing, we expected this
189
assertEquals("failed save5 w backup", "version 3",
190                  FileOps.readFileAsString(writeTo));
191
192     // Make sure that the backup file no longer exists since it was copied over the original
193
try {
194       FileOps.readFileAsString(backup);
195       fail("The backup file should no longer exist.");
196     }
197     catch(FileNotFoundException e) { } //do nothing, we expected this
198

199     // Test that save fails if the file is write-protected.
200
writeTo.setReadOnly();
201     try {
202       FileOps.saveFile(new FileOps.DefaultFileSaver(writeTo) {
203         public boolean shouldBackup () { return true; }
204         public void saveTo(OutputStream os) throws IOException {
205           String JavaDoc output = "version 6";
206           os.write(output.getBytes());
207         }
208       });
209       fail("The file to be saved was read-only!");
210     }
211     catch(IOException ioe){ } //do nothing, we expected this
212
assertEquals("failed save6 w backup", "version 3",
213                  FileOps.readFileAsString(writeTo));
214
215     // Make sure that the backup file still doesn't exist since the file
216
// was read-only.
217
try {
218       FileOps.readFileAsString(backup);
219       fail("The backup file should no longer exist.");
220     }
221     catch(FileNotFoundException e) { } //do nothing, we expected this
222
}
223
224   /**
225    * This tests that packageExplore correctly runs through and returns
226    * non-empty packages
227    */

228   public void testPackageExplore() throws IOException {
229     File rootDir = FileOps.createTempDirectory("fileOpsTest");
230     File subDir0 = new File(rootDir, "sub0");
231     subDir0.mkdir();
232     File subDir1 = new File(rootDir, "sub1");
233     subDir1.mkdir();
234     File subsubDir0 = new File(subDir0, "subsub0");
235     subsubDir0.mkdir();
236     File javasubsub = new File(subsubDir0, "aclass.java");
237     FileOps.writeStringToFile(javasubsub, "contents of this file are unimportant");
238     File javasub1 = new File(subDir1, "myclass.java");
239     FileOps.writeStringToFile(javasub1, "this file is pretty much empty");
240     File javaroot = new File(rootDir, "someclass.java");
241     FileOps.writeStringToFile(javaroot, "i can write anything i want here");
242
243     LinkedList JavaDoc packages = FileOps.packageExplore("hello", rootDir);
244     assertEquals("package count a", 3, packages.size());
245     assertTrue("packages contents a0", packages.contains("hello.sub0.subsub0"));
246     assertTrue("packages contents a1", packages.contains("hello.sub1"));
247     assertTrue("packages contents a2", packages.contains("hello"));
248
249     //Now add a .java file to the root directory and check that the default directory
250
//is not added
251
packages = FileOps.packageExplore("", rootDir);
252     assertEquals("package count b", 2, packages.size());
253     assertTrue("packages contents b0", packages.contains("sub0.subsub0"));
254     assertTrue("packages contents b1", packages.contains("sub1"));
255
256
257     assertTrue("deleting temp directory", FileOps.deleteDirectory(rootDir));
258   }
259
260   /** Tests that non-empty directories can be deleted on exit. */
261   public void xtestDeleteDirectoryOnExit() throws IOException, InterruptedException JavaDoc {
262   
263     File tempDir = FileOps.createTempDirectory("DrJavaTestTempDir");
264     assertTrue("tempDir exists", tempDir.exists());
265     File dir1 = new File(tempDir, "dir1");
266     dir1.mkdir();
267     assertTrue("dir1 exists", dir1.exists());
268     assertTrue("dir1 is directory", dir1.isDirectory());
269     File file1 = new File(dir1, "file1");
270     file1.createNewFile(); // Should always succeed because dir1 was just created
271
assertTrue("file1 exists", file1.exists());
272     File dir2 = new File(dir1, "dir2");
273     dir2.mkdir();
274     assertTrue("dir2 exists", dir2.exists());
275     assertTrue("dir2 is directory", dir1.isDirectory());
276     File file2 = new File(dir2, "file2");
277     file2.createNewFile();
278     assertTrue("file2 exists", file2.exists());
279
280     String JavaDoc className = "edu.rice.cs.util.FileOpsTest";
281     String JavaDoc[] args = new String JavaDoc[] {dir1.getAbsolutePath() }; // args = {<Fully qualified name of dir1>}
282

283     Process JavaDoc process = ExecJVM.runJVMPropagateClassPath(className, args, FileOption.NULL_FILE);
284     int status = process.waitFor();
285     assertEquals("Delete on exit test exited with an error!", 0, status);
286
287     assertTrue("dir1 should be deleted", ! dir1.exists());
288     assertTrue("file1 should be deleted", ! file1.exists());
289     assertTrue("dir2 should be deleted", ! dir2.exists());
290     assertTrue("file2 should be deleted", ! file2.exists());
291     /* If this test passes, tempDir should be deleted when the this JVM exits. */
292   }
293
294   public void testSplitFile() {
295     String JavaDoc[] parts = new String JavaDoc[]{"","home","username","dir"};
296     String JavaDoc path1 = "";
297     for (String JavaDoc s : parts) {
298       path1 += s + File.separator;
299     }
300
301     File f = new File(path1);
302     String JavaDoc[] res = FileOps.splitFile(f);
303
304     assertTrue( "Inconsitent results. Expected " +
305                java.util.Arrays.asList(parts).toString() + ", but found " +
306                java.util.Arrays.asList(res).toString(),
307                java.util.Arrays.equals(parts,res));
308   }
309
310   private String JavaDoc fixPathFormat(String JavaDoc s){
311     return s.replace('\\', '/');
312   }
313
314   public void testMakeRelativeTo() throws IOException, SecurityException JavaDoc {
315     File base, abs;
316
317     base = new File("src/test1/test2/file.txt");
318     abs = new File("built/test1/test2/file.txt");
319     assertEquals("Wrong Relative Path 1", "../../../built/test1/test2/file.txt",
320                  fixPathFormat(FileOps.makeRelativeTo(abs,base).getPath()));
321     base = new File("file.txt");
322     abs = new File("built/test1/test2/file.txt");
323     assertEquals("Wrong Relative Path 2", "built/test1/test2/file.txt",
324                  fixPathFormat(FileOps.makeRelativeTo(abs,base).getPath()));
325     base = new File("built/test1/test2test/file.txt");
326     abs = new File("built/test1/test2/file.txt");
327     assertEquals("Wrong Relative Path 3", "../test2/file.txt",
328                  fixPathFormat(FileOps.makeRelativeTo(abs,base).getPath()));
329     base = new File("file.txt");
330     abs = new File("test.txt");
331     assertEquals("Wrong Relative Path 4", "test.txt",
332                  fixPathFormat(FileOps.makeRelativeTo(abs,base).getPath()));
333   }
334
335   /** Main method to be called by testDeleteDirectoryOnExit. Runs in a new JVM so the files can be deleted.
336    * Exits with status 1 if wrong number of arguments. Exits with status 2 if file doesn't exist
337    * @param args should contain the file name of the directory to delete on exit
338    */

339   public static void main(String JavaDoc[] args) {
340     if (args.length != 1) System.exit(1);
341
342     File dir = new File(args[0]);
343     if (! dir.exists()) System.exit(2);
344     FileOps.deleteDirectoryOnExit(dir);
345
346     // OK, exit cleanly
347
System.exit(0);
348   }
349   
350   public void testConvertToAbsolutePathEntries() {
351     String JavaDoc ud = System.getProperty("user.dir");
352     String JavaDoc f = System.getProperty("file.separator");
353     String JavaDoc p = System.getProperty("path.separator");
354     String JavaDoc expected, actual, input;
355     
356     input = "."+p+"drjava"+p+p+f+"home"+f+"foo"+f+"junit.jar";
357     expected = ud+f+"."+p+ud+f+"drjava"+p+ud+p+(new File(f+"home"+f+"foo"+f+"junit.jar")).getAbsolutePath();
358     actual = FileOps.convertToAbsolutePathEntries(input);
359     assertEquals("testConvertToAbsolutePathEntries for several paths failed, input = '" + input + "', expected = '" +
360                  expected + "', actual = '" + actual + "'", expected, actual);
361     input = "";
362     expected = ud;
363     actual = FileOps.convertToAbsolutePathEntries(input);
364     assertEquals("testConvertToAbsolutePathEntries for empty path failed, input = '" + input + "', expected = '" +
365                  expected + "', actual = '" + actual + "'", expected, actual);
366     input = p + p + p + ".";
367     expected = ud + p + ud + p + ud + p + ud + f + ".";
368     actual = FileOps.convertToAbsolutePathEntries(input);
369     assertEquals("testConvertToAbsolutePathEntries for several empty paths failed, input = '" + input +
370                  "', expected = '" +expected+"', actual = '" + actual + "'", expected, actual);
371     input = p + p;
372     expected = ud + p + ud + p + ud;
373     actual = FileOps.convertToAbsolutePathEntries(input);
374     assertEquals("testConvertToAbsolutePathEntries for trailing empty paths failed, input = '" + input +
375                  "', expected = '" + expected + "', actual = '" + actual + "'", expected, actual);
376   }
377   
378   /** Tests getFilesInDir. */
379   public void testGetFiles() throws IOException {
380     File dir1 = FileOps.createTempDirectory("DrJavaTestTempDir");
381     assertTrue("dir1 exists", dir1.exists());
382     File file1a = File.createTempFile("DrJavaTest-", ".temp", dir1).getCanonicalFile();
383     assertTrue("file1a exists", file1a.exists());
384     File file1b = File.createTempFile("DrJava-", ".temp", dir1).getCanonicalFile();
385     assertTrue("file1b exists", file1b.exists());
386     File dir2 = FileOps.createTempDirectory("DrJavaTestDir-", dir1).getCanonicalFile();
387     assertTrue("dir2 exists", dir2.exists());
388     File file2 = File.createTempFile("DrJavaTest-", ".temp", dir2).getCanonicalFile();
389     assertTrue("file2 exists", file2.exists());
390     
391     FileFilter ff = new FileFilter() {
392         public boolean accept(File f) {
393           if (f.isDirectory()) return true;
394           String JavaDoc name = f.getName();
395           return name.startsWith("DrJavaTest");
396         }
397     };
398     
399     Set JavaDoc<File> res1 = new TreeSet JavaDoc<File>(Arrays.asList(new File[] {file1a}));
400     Set JavaDoc<File> res2 = new TreeSet JavaDoc<File>(Arrays.asList(new File[] {file1a, file2}));
401     
402     Set JavaDoc<File> nrfiles = new TreeSet JavaDoc<File>();
403     for(File f : FileOps.getFilesInDir(dir1, false, ff)) {
404       nrfiles.add(f.getCanonicalFile());
405     }
406
407     Set JavaDoc<File> rfiles = new TreeSet JavaDoc<File>();
408     for(File f : FileOps.getFilesInDir(dir1, true, ff)) {
409       rfiles.add(f.getCanonicalFile());
410     }
411         
412     assertEquals("non-recursive FilesInDir test", res1, nrfiles);
413     assertEquals("recursive FileInDir test", res2, rfiles);
414   }
415 }
416
Popular Tags