7145c7f8dcc5b604e34274470d4bfdaeb4a72b6e
[utils] / support / general / src / test / java / org / wamblee / io / FileSystemUtils.java
1 /*
2  * Copyright 2005-2010 the original author or authors.
3  * 
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  * 
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  * 
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */ 
16 package org.wamblee.io;
17
18 import java.io.File;
19 import java.io.FileInputStream;
20 import java.io.FileOutputStream;
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.OutputStream;
24 import java.io.UnsupportedEncodingException;
25 import java.net.URL;
26 import java.net.URLDecoder;
27 import java.nio.MappedByteBuffer;
28 import java.nio.channels.FileChannel;
29 import java.security.CodeSource;
30 import java.util.logging.Level;
31 import java.util.logging.Logger;
32
33 import junit.framework.Assert;
34 import junit.framework.TestCase;
35
36 /**
37  * File system utilities.
38  * 
39  * @author Erik Brakkee
40  */
41 public final class FileSystemUtils {
42     private static final Logger LOG = Logger.getLogger(FileSystemUtils.class.getName());
43
44     /**
45      * Test output directory relative to the sub project.
46      */
47     private static final String TEST_OUTPUT_DIR = "../target/testoutput";
48
49     /**
50      * Test input directory relative to the sub project.
51      */
52     private static final String TEST_INPUT_DIR = "../src/test/resources";
53
54     /*
55      * Disabled.
56      */
57     private FileSystemUtils() {
58         // Empty
59     }
60
61     /**
62      * Deletes a directory recursively. The test case will fail if the directory
63      * does not exist or if deletion fails.
64      * 
65      * @param aDir
66      *            Directory to delete.
67      */
68     public static void deleteDirRecursively(String aDir) {
69         deleteDirRecursively(new File(aDir));
70     }
71
72     /**
73      * Deletes a directory recursively. See {@link #deleteDirRecursively}.
74      * 
75      * @param aDir
76      *            Directory.
77      */
78     public static void deleteDirRecursively(File aDir) {
79         TestCase.assertTrue(aDir.isDirectory());
80
81         for (File file : aDir.listFiles()) {
82             if (file.isDirectory()) {
83                 deleteDirRecursively(file);
84             } else {
85                 delete(file);
86             }
87         }
88
89         delete(aDir);
90     }
91
92     /**
93      * Deletes a file or directory. The test case will fail if the file or
94      * directory does not exist or if deletion fails. Deletion of a non-empty
95      * directory will always fail.
96      * 
97      * @param aFile
98      *            File or directory to delete.
99      */
100     public static void delete(File aFile) {
101         TestCase.assertTrue(aFile.delete());
102     }
103
104     /**
105      * Gets a path relative to a sub project. This utility should be used to
106      * easily access file paths within a subproject without requiring any
107      * specific Eclipse configuration.
108      * 
109      * @param aRelativePath
110      *            Relative path.
111      * @param aTestClass
112      *            Test class.
113      */
114     public static File getPath(String aRelativePath, Class aTestClass) {
115         CodeSource source = aTestClass.getProtectionDomain().getCodeSource();
116
117         if (source == null) {
118             LOG.warning("Could not obtain path for '" + aRelativePath +
119                 "' for class " + aTestClass + ", using relative path as is");
120
121             return new File(aRelativePath);
122         }
123
124         URL location = source.getLocation();
125         String protocol = location.getProtocol();
126
127         if (!protocol.equals("file")) {
128             LOG.warning("protocol is not 'file': " + location);
129
130             return new File(aRelativePath);
131         }
132
133         String path = location.getPath();
134
135         try {
136             path = URLDecoder.decode(location.getPath(), "UTF-8");
137         } catch (UnsupportedEncodingException e) {
138             // ignore it.. just don't decode
139             LOG.log(Level.WARNING, "Decoding path failed: '" + location.getPath() + "'", e);
140         }
141
142         return new File(new File(path).getParentFile(), aRelativePath);
143     }
144
145     /**
146      * Ensures that a directory hierarchy exists (recursively if needed). If it
147      * is not possible to create the directory, then the test case will fail.
148      * 
149      * @param aDir
150      *            Directory to create.
151      */
152     public static void createDir(File aDir) {
153         if (aDir.exists() && !aDir.isDirectory()) {
154             TestCase.fail("'" + aDir +
155                 "' already exists and is not a directory");
156         }
157
158         if (aDir.exists()) {
159             return;
160         }
161
162         createDir(aDir.getParentFile());
163         TestCase.assertTrue("Could not create '" + aDir + "'", aDir.mkdir());
164     }
165
166     /**
167      * Creates a file in a directory.
168      * 
169      * @param aDir
170      *            Directory path. Will be created if it does not exist.
171      * @param aName
172      *            Filename.
173      * @param aContents
174      *            Contents.
175      */
176     public static void createFile(File aDir, String aName, InputStream aContents) {
177         createDir(aDir);
178
179         try {
180             OutputStream os = new FileOutputStream(new File(aDir, aName));
181             copyStream(aContents, os);
182         } catch (IOException e) {
183             e.printStackTrace();
184             TestCase.fail(e.getMessage());
185         }
186     }
187
188     /**
189      * Gets the test output directory for a specific test class.
190      * 
191      * @param aTestClass
192      *            Test class.
193      * @return Test output directory.
194      */
195     public static File getTestOutputDir(Class aTestClass) {
196         File file = getPath(TEST_OUTPUT_DIR, aTestClass);
197         String className = aTestClass.getName();
198         String classRelPath = className.replaceAll("\\.", "/");
199
200         return new File(file, classRelPath);
201     }
202
203     /**
204      * Gets the test input directory for a specific test class.
205      * 
206      * @param aTestClass
207      *            Test class.
208      * @return Test input directory.
209      */
210     public static File getTestInputDir(Class aTestClass) {
211         File file = getPath(TEST_INPUT_DIR, aTestClass);
212         String packageName = aTestClass.getPackage().getName();
213         String packagePath = packageName.replaceAll("\\.", "/");
214
215         return new File(file, packagePath);
216     }
217
218     /**
219      * Creates a directory hierarchy for the output directory of a test class if
220      * needed.
221      * 
222      * @param aTestClass
223      *            Test class
224      * @return Test directory.
225      */
226     public static File createTestOutputDir(Class aTestClass) {
227         File file = getTestOutputDir(aTestClass);
228         createDir(file);
229
230         return file;
231     }
232
233     /**
234      * Gets a test output file name. This returns a File object representing the
235      * output file and ensures that the directory where the file will be created
236      * already exists.
237      * 
238      * @param aName
239      *            Name of the file.
240      * @param aTestClass
241      *            Test class.
242      * @return File.
243      */
244     public static File getTestOutputFile(String aName, Class aTestClass) {
245         File file = new File(getTestOutputDir(aTestClass), aName);
246         createDir(file.getParentFile());
247
248         return file;
249     }
250
251     public static String read(InputStream aIs) throws IOException {
252         try {
253             StringBuffer buffer = new StringBuffer();
254             int c;
255
256             while ((c = aIs.read()) != -1) {
257                 buffer.append((char) c);
258             }
259
260             return buffer.toString();
261         } finally {
262             aIs.close();
263         }
264     }
265
266     /**
267      * Copies an input stream to an output stream.
268      * 
269      * @param aIs
270      *            Input stream.
271      * @param aOs
272      *            Output stream.
273      */
274     public static void copyStream(InputStream aIs, OutputStream aOs) {
275         try {
276             int c;
277
278             while ((c = aIs.read()) != -1) {
279                 aOs.write(c);
280             }
281
282             aIs.close();
283             aOs.close();
284         } catch (IOException e) {
285             e.printStackTrace();
286             Assert.fail(e.getMessage());
287         }
288     }
289
290     /**
291      * Recursively copy a directory.
292      * 
293      * @param aSrc
294      *            Source directory
295      * @param aTarget
296      *            Target directory.
297      */
298     public static void copyDir(File aSrc, File aTarget) {
299         Assert.assertTrue(aSrc.isDirectory());
300         Assert.assertTrue(!aTarget.exists());
301
302         if (!aTarget.mkdirs()) { 
303             Assert.fail("Could not create target directory '" + aTarget + "'");
304         }
305
306         File[] files = aSrc.listFiles();
307
308         for (int i = 0; i < files.length; i++) {
309             File file = files[i];
310
311             if (file.isDirectory()) {
312                 if (!file.getName().equals(".svn")) {
313                     copyDir(new File(aSrc, file.getName()), new File(aTarget,
314                         file.getName()));
315                 }
316             } else {
317                 copyFile(file, new File(aTarget, file.getName()));
318             }
319         }
320     }
321
322     /**
323      * Copy a file. If copying fails then the testcase will fail.
324      * 
325      * @param aSrc
326      *            Source file.
327      * @param aTarget
328      *            Target file.
329      */
330     public static void copyFile(File aSrc, File aTarget) {
331         try {
332             FileInputStream fis = new FileInputStream(aSrc);
333             FileOutputStream fos = new FileOutputStream(aTarget);
334             FileChannel fcin = fis.getChannel();
335             FileChannel fcout = fos.getChannel();
336
337             // map input file
338             MappedByteBuffer mbb = fcin.map(FileChannel.MapMode.READ_ONLY, 0,
339                 fcin.size());
340
341             // do the file copy
342             fcout.write(mbb);
343
344             // finish up
345             fcin.close();
346             fcout.close();
347             fis.close();
348             fos.close();
349         } catch (IOException e) {
350             Assert.assertTrue("Copying file " + aSrc.getPath() + " to " +
351                 aTarget.getPath() + " failed.", false);
352         }
353     }
354
355     /**
356      * Remove all files within a given directory including the directory itself.
357      * This only attempts to remove regular files and not directories within the
358      * directory. If the directory contains a nested directory, the deletion
359      * will fail. The test case will fail if this fails.
360      * 
361      * @param aDir
362      *            Directory to remove.
363      */
364     public static void deleteDir(File aDir) {
365         cleanDir(aDir);
366         delete(aDir);
367     }
368
369     /**
370      * Remove all regular files within a given directory.
371      * 
372      * @param outputDirName
373      */
374     public static void cleanDir(File aDir) {
375         if (!aDir.exists()) {
376             return; // nothing to do.
377         }
378
379         File[] entries = aDir.listFiles();
380
381         for (int i = 0; i < entries.length; i++) {
382             File file = entries[i];
383
384             if (file.isFile()) {
385                 Assert.assertTrue("Could not delete " + entries[i].getPath(),
386                     entries[i].delete());
387             }
388         }
389     }
390 }