2 * Copyright 2006 the original author or authors.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.wamblee.io;
18 import junit.framework.Assert;
19 import junit.framework.TestCase;
21 import org.apache.commons.logging.Log;
22 import org.apache.commons.logging.LogFactory;
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;
33 import java.net.URLDecoder;
35 import java.nio.MappedByteBuffer;
36 import java.nio.channels.FileChannel;
38 import java.security.CodeSource;
41 * File system utilities.
43 * @author Erik Brakkee
45 public final class FileSystemUtils {
46 private static final Log LOG = LogFactory.getLog(FileSystemUtils.class);
49 * Test output directory relative to the sub project.
51 private static final String TEST_OUTPUT_DIR = "../target/testoutput";
54 * Test input directory relative to the sub project.
56 private static final String TEST_INPUT_DIR = "../src/test/resources";
61 private FileSystemUtils() {
66 * Deletes a directory recursively. The test case will fail if the directory
67 * does not exist or if deletion fails.
70 * Directory to delete.
72 public static void deleteDirRecursively(String aDir) {
73 deleteDirRecursively(new File(aDir));
77 * Deletes a directory recursively. See {@link #deleteDirRecursively}.
82 public static void deleteDirRecursively(File aDir) {
83 TestCase.assertTrue(aDir.isDirectory());
85 for (File file : aDir.listFiles()) {
86 if (file.isDirectory()) {
87 deleteDirRecursively(file);
97 * Deletes a file or directory. The test case will fail if the file or
98 * directory does not exist or if deletion fails. Deletion of a non-empty
99 * directory will always fail.
102 * File or directory to delete.
104 public static void delete(File aFile) {
105 TestCase.assertTrue(aFile.delete());
109 * Gets a path relative to a sub project. This utility should be used to
110 * easily access file paths within a subproject without requiring any
111 * specific Eclipse configuration.
113 * @param aRelativePath
118 public static File getPath(String aRelativePath, Class aTestClass) {
119 CodeSource source = aTestClass.getProtectionDomain().getCodeSource();
121 if (source == null) {
122 LOG.warn("Could not obtain path for '" + aRelativePath +
123 "' for class " + aTestClass + ", using relative path as is");
125 return new File(aRelativePath);
128 URL location = source.getLocation();
129 String protocol = location.getProtocol();
131 if (!protocol.equals("file")) {
132 LOG.warn("protocol is not 'file': " + location);
134 return new File(aRelativePath);
137 String path = location.getPath();
140 path = URLDecoder.decode(location.getPath(), "UTF-8");
141 } catch (UnsupportedEncodingException e) {
142 // ignore it.. just don't decode
143 LOG.warn("Decoding path failed: '" + location.getPath() + "'", e);
146 return new File(new File(path).getParentFile(), aRelativePath);
150 * Ensures that a directory hierarchy exists (recursively if needed). If it
151 * is not possible to create the directory, then the test case will fail.
154 * Directory to create.
156 public static void createDir(File aDir) {
157 if (aDir.exists() && !aDir.isDirectory()) {
158 TestCase.fail("'" + aDir +
159 "' already exists and is not a directory");
166 createDir(aDir.getParentFile());
167 TestCase.assertTrue("Could not create '" + aDir + "'", aDir.mkdir());
171 * Creates a file in a directory.
174 * Directory path. Will be created if it does not exist.
180 public static void createFile(File aDir, String aName, InputStream aContents) {
184 OutputStream os = new FileOutputStream(new File(aDir, aName));
185 copyStream(aContents, os);
186 } catch (IOException e) {
188 TestCase.fail(e.getMessage());
193 * Gets the test output directory for a specific test class.
197 * @return Test output directory.
199 public static File getTestOutputDir(Class aTestClass) {
200 File file = getPath(TEST_OUTPUT_DIR, aTestClass);
201 String className = aTestClass.getName();
202 String classRelPath = className.replaceAll("\\.", "/");
204 return new File(file, classRelPath);
208 * Gets the test input directory for a specific test class.
212 * @return Test input directory.
214 public static File getTestInputDir(Class aTestClass) {
215 File file = getPath(TEST_INPUT_DIR, aTestClass);
216 String packageName = aTestClass.getPackage().getName();
217 String packagePath = packageName.replaceAll("\\.", "/");
219 return new File(file, packagePath);
223 * Creates a directory hierarchy for the output directory of a test class if
228 * @return Test directory.
230 public static File createTestOutputDir(Class aTestClass) {
231 File file = getTestOutputDir(aTestClass);
238 * Gets a test output file name. This returns a File object representing the
239 * output file and ensures that the directory where the file will be created
248 public static File getTestOutputFile(String aName, Class aTestClass) {
249 File file = new File(getTestOutputDir(aTestClass), aName);
250 createDir(file.getParentFile());
255 public static String read(InputStream aIs) throws IOException {
257 StringBuffer buffer = new StringBuffer();
260 while ((c = aIs.read()) != -1) {
261 buffer.append((char) c);
264 return buffer.toString();
271 * Copies an input stream to an output stream.
278 public static void copyStream(InputStream aIs, OutputStream aOs) {
282 while ((c = aIs.read()) != -1) {
288 } catch (IOException e) {
290 Assert.fail(e.getMessage());
295 * Recursively copy a directory.
302 public static void copyDir(File aSrc, File aTarget) {
303 Assert.assertTrue(aSrc.isDirectory());
304 Assert.assertTrue(!aTarget.exists());
308 File[] files = aSrc.listFiles();
310 for (int i = 0; i < files.length; i++) {
311 File file = files[i];
313 if (file.isDirectory()) {
314 if (!file.getName().equals(".svn")) {
315 copyDir(new File(aSrc, file.getName()), new File(aTarget,
319 copyFile(file, new File(aTarget, file.getName()));
325 * Copy a file. If copying fails then the testcase will fail.
332 public static void copyFile(File aSrc, File aTarget) {
334 FileInputStream fis = new FileInputStream(aSrc);
335 FileOutputStream fos = new FileOutputStream(aTarget);
336 FileChannel fcin = fis.getChannel();
337 FileChannel fcout = fos.getChannel();
340 MappedByteBuffer mbb = fcin.map(FileChannel.MapMode.READ_ONLY, 0,
351 } catch (IOException e) {
352 Assert.assertTrue("Copying file " + aSrc.getPath() + " to " +
353 aTarget.getPath() + " failed.", false);
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.
364 * Directory to remove.
366 public static void deleteDir(File aDir) {
372 * Remove all regular files within a given directory.
374 * @param outputDirName
376 public static void cleanDir(File aDir) {
377 if (!aDir.exists()) {
378 return; // nothing to do.
381 File[] entries = aDir.listFiles();
383 for (int i = 0; i < entries.length; i++) {
384 File file = entries[i];
387 Assert.assertTrue("Could not delete " + entries[i].getPath(),
388 entries[i].delete());