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