fd507caf41084334ed746ed6fa55a98dfcbe971e
[utils] / support / general / src / test / java / org / wamblee / io / FileSystemUtils.java
1 /*
2  * Copyright 2006 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 junit.framework.Assert;
19 import junit.framework.TestCase;
20
21 import org.apache.commons.logging.Log;
22 import org.apache.commons.logging.LogFactory;
23
24 import java.io.File;
25 import java.io.FileInputStream;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.io.InputStream;
29 import java.io.OutputStream;
30 import java.io.UnsupportedEncodingException;
31
32 import java.net.URL;
33 import java.net.URLDecoder;
34
35 import java.nio.MappedByteBuffer;
36 import java.nio.channels.FileChannel;
37
38 import java.security.CodeSource;
39
40
41 /**
42  * File system utilities.
43  *
44  * @author Erik Brakkee
45  */
46 public final class FileSystemUtils {
47     private static final Log LOG = LogFactory.getLog(FileSystemUtils.class);
48
49     /**
50      * Test output directory relative to the sub project.
51      */
52     private static final String TEST_OUTPUT_DIR = "../target/testoutput";
53
54     /**
55      * Test input directory relative to the sub project.
56      */
57     private static final String TEST_INPUT_DIR = "../src/test/resources";
58
59     /*
60      * Disabled.
61      *
62      */
63     private FileSystemUtils() {
64         // Empty
65     }
66
67     /**
68      * Deletes a directory recursively. The test case will fail if the directory
69      * does not exist or if deletion fails.
70      *
71      * @param aDir
72      *            Directory to delete.
73      */
74     public static void deleteDirRecursively(String aDir) {
75         deleteDirRecursively(new File(aDir));
76     }
77
78     /**
79      * Deletes a directory recursively. See {@link #deleteDirRecursively}.
80      *
81      * @param aDir
82      *            Directory.
83      */
84     public static void deleteDirRecursively(File aDir) {
85         TestCase.assertTrue(aDir.isDirectory());
86
87         for (File file : aDir.listFiles()) {
88             if (file.isDirectory()) {
89                 deleteDirRecursively(file);
90             } else {
91                 delete(file);
92             }
93         }
94
95         delete(aDir);
96     }
97
98     /**
99      * Deletes a file or directory. The test case will fail if the file or
100      * directory does not exist or if deletion fails. Deletion of a non-empty
101      * directory will always fail.
102      *
103      * @param aFile
104      *            File or directory to delete.
105      */
106     public static void delete(File aFile) {
107         TestCase.assertTrue(aFile.delete());
108     }
109
110     /**
111      * Gets a path relative to a sub project. This utility should be used to
112      * easily access file paths within a subproject without requiring any
113      * specific Eclipse configuration.
114      *
115      * @param aRelativePath
116      *            Relative path.
117      * @param aTestClass
118      *            Test class.
119      */
120     public static File getPath(String aRelativePath, Class aTestClass) {
121         CodeSource source = aTestClass.getProtectionDomain().getCodeSource();
122
123         if (source == null) {
124             LOG.warn("Could not obtain path for '" + aRelativePath +
125                 "' for class " + aTestClass + ", using relative path as is");
126
127             return new File(aRelativePath);
128         }
129
130         URL location = source.getLocation();
131         String protocol = location.getProtocol();
132
133         if (!protocol.equals("file")) {
134             LOG.warn("protocol is not 'file': " + location);
135
136             return new File(aRelativePath);
137         }
138
139         String path = location.getPath();
140
141         try {
142             path = URLDecoder.decode(location.getPath(), "UTF-8");
143         } catch (UnsupportedEncodingException e) {
144             // ignore it.. just don't decode
145             LOG.warn("Decoding path failed: '" + location.getPath() + "'", e);
146         }
147
148         return new File(new File(path).getParentFile(), aRelativePath);
149     }
150
151     /**
152      * Ensures that a directory hierarchy exists (recursively if needed). If it
153      * is not possible to create the directory, then the test case will fail.
154      *
155      * @param aDir
156      *            Directory to create.
157      */
158     public static void createDir(File aDir) {
159         if (aDir.exists() && !aDir.isDirectory()) {
160             TestCase.fail("'" + aDir +
161                 "' already exists and is not a directory");
162         }
163
164         if (aDir.exists()) {
165             return;
166         }
167
168         createDir(aDir.getParentFile());
169         TestCase.assertTrue("Could not create '" + aDir + "'", aDir.mkdir());
170     }
171
172     /**
173      * Creates a file in a directory.
174      * @param aDir Directory path. Will be created if it does not exist.
175      * @param aName Filename.
176      * @param aContents 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         aTarget.mkdirs();
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()),
314                         new File(aTarget, 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 }