You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@commons.apache.org by gg...@apache.org on 2021/07/16 14:11:23 UTC
[commons-vfs] 02/02: Sort members.
This is an automated email from the ASF dual-hosted git repository.
ggregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-vfs.git
commit 82534ffe56a17c835af63264679487325c123c40
Author: Gary Gregory <ga...@gmail.com>
AuthorDate: Fri Jul 16 10:11:17 2021 -0400
Sort members.
---
.../commons/vfs2/AbstractProviderTestCase.java | 344 +++++------
.../org/apache/commons/vfs2/AbstractTestSuite.java | 204 +++----
.../java/org/apache/commons/vfs2/ContentTests.java | 382 ++++++------
.../java/org/apache/commons/vfs2/FileInfo.java | 26 +-
.../commons/vfs2/FileSystemExceptionTest.java | 20 +-
.../vfs2/FileSystemManagerFactoryTestCase.java | 28 +-
.../apache/commons/vfs2/FileSystemOptionsTest.java | 48 +-
.../java/org/apache/commons/vfs2/FileTypeTest.java | 32 +-
.../org/apache/commons/vfs2/LastModifiedTests.java | 48 +-
.../java/org/apache/commons/vfs2/NamingTests.java | 462 +++++++-------
.../commons/vfs2/PatternFileSelectorTest.java | 48 +-
.../org/apache/commons/vfs2/PermissionsTests.java | 110 ++--
.../commons/vfs2/ProviderCacheStrategyTests.java | 60 +-
.../apache/commons/vfs2/ProviderDeleteTests.java | 50 +-
.../commons/vfs2/ProviderRandomReadWriteTests.java | 18 +-
.../org/apache/commons/vfs2/ProviderReadTests.java | 200 +++---
.../apache/commons/vfs2/ProviderRenameTests.java | 84 +--
.../apache/commons/vfs2/ProviderTestConfig.java | 20 +-
.../commons/vfs2/ProviderWriteAppendTests.java | 18 +-
.../apache/commons/vfs2/ProviderWriteTests.java | 672 ++++++++++-----------
.../test/java/org/apache/commons/vfs2/RunTest.java | 22 +-
.../apache/commons/vfs2/VerifyingFileSelector.java | 46 +-
.../vfs2/cache/AbstractFilesCacheTestsBase.java | 48 +-
.../commons/vfs2/cache/LRUFilesCacheTests.java | 18 +-
.../commons/vfs2/cache/NullFilesCacheTests.java | 22 +-
.../commons/vfs2/cache/WeakRefFilesCacheTests.java | 10 +-
.../commons/vfs2/filter/AgeFileFilterTest.java | 38 +-
.../commons/vfs2/filter/AndFileFilterTest.java | 180 +++---
.../apache/commons/vfs2/filter/BaseFilterTest.java | 306 +++++-----
.../vfs2/filter/CanExecuteFileFilterTest.java | 46 +-
.../commons/vfs2/filter/CanReadFileFilterTest.java | 56 +-
.../vfs2/filter/CanWriteFileFilterTest.java | 56 +-
.../vfs2/filter/DirectoryAndFileFilterTest.java | 82 +--
.../commons/vfs2/filter/EmptyFileFilterTest.java | 44 +-
.../commons/vfs2/filter/HiddenFileFilterTest.java | 36 +-
.../commons/vfs2/filter/OrFileFilterTest.java | 138 ++---
.../vfs2/filter/RegexFileFilterTestCase.java | 28 +-
.../commons/vfs2/filter/SizeFileFilterTest.java | 104 ++--
.../vfs2/filter/SymbolicLinkFileFilterTest.java | 42 +-
.../commons/vfs2/impl/DefaultFileMonitorTest.java | 8 +-
.../vfs2/impl/DefaultFileSystemManagerTest.java | 10 +-
.../commons/vfs2/impl/VfsClassLoaderTests.java | 130 ++--
.../vfs2/operations/BasicOperationsTestCase.java | 46 +-
.../commons/vfs2/perf/FileNamePerformance.java | 20 +-
.../vfs2/provider/AbstractFileNameTest.java | 10 +-
.../commons/vfs2/provider/UriParserTestCase.java | 28 +-
.../ftps/AbstractFtpsProviderTestCase.java | 74 +--
.../ftps/FtpsProviderExplicitTestCase.java | 14 +-
.../ftps/FtpsProviderImplicitTestCase.java | 14 +-
.../vfs2/provider/hdfs/HdfsFileProviderTest.java | 56 +-
.../vfs2/provider/jar/NestedJarTestCase.java | 18 +-
.../vfs2/provider/local/ConversionTestCase.java | 26 +-
.../vfs2/provider/local/WindowsFileNameTests.java | 62 +-
.../vfs2/provider/ram/CustomRamProviderTest.java | 168 +++---
.../vfs2/provider/ram/RamProviderTestCase.java | 38 +-
.../vfs2/provider/res/ResSchemeTestCase.java | 12 +-
.../provider/res/ResourceProviderTestCase.java | 18 +-
.../commons/vfs2/provider/res/Vfs444TestCase.java | 80 +--
.../sftp/AbstractSftpProviderTestCase.java | 654 ++++++++++----------
.../SftpProviderClosedExecChannelTestCase.java | 10 +-
.../sftp/SftpProviderStreamProxyModeTestCase.java | 10 +-
.../vfs2/provider/sftp/SftpProviderTestCase.java | 10 +-
.../provider/tar/CreateFileSystemTestCase.java | 8 +-
.../vfs2/provider/tar/LargeTarTestCase.java | 156 ++---
.../vfs2/provider/tar/NestedTarTestCase.java | 20 +-
.../vfs2/provider/tar/NestedTbz2TestCase.java | 20 +-
.../vfs2/provider/tar/NestedTgzTestCase.java | 20 +-
.../vfs2/provider/tar/TarFileObjectTestCase.java | 52 +-
.../vfs2/provider/tar/TarProviderTestCase.java | 18 +-
.../vfs2/provider/tar/Tbz2ProviderTestCase.java | 18 +-
.../vfs2/provider/tar/TgzProviderTestCase.java | 20 +-
.../provider/temp/TemporaryProviderTestCase.java | 14 +-
.../provider/test/GenericFileNameTestCase.java | 74 +--
.../vfs2/provider/test/JunctionProviderConfig.java | 40 +-
.../commons/vfs2/provider/test/JunctionTests.java | 52 +-
.../vfs2/provider/url/UrlHttpProviderTestCase.java | 14 +-
.../vfs2/provider/url/UrlProviderTestCase.java | 14 +-
.../vfs2/provider/zip/FileLockTestCase.java | 70 +--
.../vfs2/provider/zip/NestedZipTestCase.java | 20 +-
.../vfs2/provider/zip/ParseXmlInZipTestCase.java | 18 +-
.../vfs2/provider/zip/ZipFileObjectTestCase.java | 54 +-
.../vfs2/provider/zip/ZipProviderTestCase.java | 20 +-
.../zip/ZipProviderWithCharsetNullTestCase.java | 20 +-
.../zip/ZipProviderWithCharsetTestCase.java | 20 +-
.../DelegatingFileSystemOptionsBuilderTest.java | 56 +-
.../commons/vfs2/util/FreeSocketPortUtil.java | 8 +-
.../apache/commons/vfs2/util/NHttpFileServer.java | 18 +-
87 files changed, 3279 insertions(+), 3277 deletions(-)
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/AbstractProviderTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/AbstractProviderTestCase.java
index ee00477..3f2db73 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/AbstractProviderTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/AbstractProviderTestCase.java
@@ -39,49 +39,160 @@ import junit.framework.TestCase;
* Works from a base folder, and assumes a particular structure under that base folder.
*/
public abstract class AbstractProviderTestCase extends AbstractVfsTestCase {
+ // Expected contents of "file1.txt"
+ public static final String FILE1_CONTENT = "This is a test file.";
+ // Expected contents of test files
+ public static final String TEST_FILE_CONTENT = "A test file.";
+ protected static Test notConfigured(final Class<?> testClass) {
+ return warning(testClass + " is not configured for tests, skipping");
+ }
+ private static Test warning(final String message) {
+ return new TestCase("warning") {
+ @Override
+ protected void runTest() {
+ System.out.println(message);
+ }
+ };
+ }
private FileObject baseFolder;
private FileObject readFolder;
private FileObject writeFolder;
+
private DefaultFileSystemManager manager;
+
private ProviderTestConfig providerConfig;
+
private Method method;
- private boolean addEmptyDir;
- // Expected contents of "file1.txt"
- public static final String FILE1_CONTENT = "This is a test file.";
+ private boolean addEmptyDir;
- // Expected contents of test files
- public static final String TEST_FILE_CONTENT = "A test file.";
+ protected void addEmptyDir(final boolean addEmptyDir) {
+ this.addEmptyDir = addEmptyDir;
+ }
/**
- * Sets the test method.
+ * Asserts that the content of a file is the same as expected. Checks the length reported by getSize() is correct,
+ * then reads the content as a byte stream and compares the result with the expected content. Assumes files are
+ * encoded using UTF-8.
*/
- public void setMethod(final Method method) {
- this.method = method;
+ protected void assertSameContent(final String expected, final FileObject file) throws Exception {
+ // Check the file exists, and is a file
+ assertTrue(file.exists());
+ assertSame(FileType.FILE, file.getType());
+ assertTrue(file.isFile());
+
+ // Get file content as a binary stream
+ final byte[] expectedBin = expected.getBytes(StandardCharsets.UTF_8);
+
+ // Check lengths
+ final FileContent content = file.getContent();
+ assertEquals("same content length", expectedBin.length, content.getSize());
+
+ // Read content into byte array
+ final InputStream instr = content.getInputStream();
+ final ByteArrayOutputStream outstr;
+ try {
+ outstr = new ByteArrayOutputStream(expectedBin.length);
+ final byte[] buffer = new byte[256];
+ int nread = 0;
+ while (nread >= 0) {
+ outstr.write(buffer, 0, nread);
+ nread = instr.read(buffer);
+ }
+ } finally {
+ instr.close();
+ }
+
+ // Compare
+ assertArrayEquals("same binary content", expectedBin, outstr.toByteArray());
}
/**
- * Configures this test.
+ * Asserts that the content of a file is the same as expected. Checks the length reported by getContentLength() is
+ * correct, then reads the content as a byte stream and compares the result with the expected content. Assumes files
+ * are encoded using UTF-8.
*/
- public void setConfig(final DefaultFileSystemManager manager, final ProviderTestConfig providerConfig,
- final FileObject baseFolder, final FileObject readFolder, final FileObject writeFolder) {
- this.manager = manager;
- this.providerConfig = providerConfig;
- this.baseFolder = baseFolder;
- this.readFolder = readFolder;
- this.writeFolder = writeFolder;
- assertNotNull("setConfig manager", manager);
- assertNotNull("setConfig providerConfig", providerConfig);
- assertNotNull("setConfig baseFolder", baseFolder);
- assertNotNull("setConfig readFolder", readFolder);
- assertNotNull("setConfig writeFolder", writeFolder);
+ protected void assertSameURLContent(final String expected, final URLConnection connection) throws Exception {
+ // Get file content as a binary stream
+ final byte[] expectedBin = expected.getBytes(StandardCharsets.UTF_8);
+
+ // Check lengths
+ assertEquals("same content length", expectedBin.length, connection.getContentLength());
+
+ // Read content into byte array
+ final InputStream instr = connection.getInputStream();
+ final ByteArrayOutputStream outstr;
+ try {
+ outstr = new ByteArrayOutputStream();
+ final byte[] buffer = new byte[256];
+ int nread = 0;
+ while (nread >= 0) {
+ outstr.write(buffer, 0, nread);
+ nread = instr.read(buffer);
+ }
+ } finally {
+ instr.close();
+ }
+
+ // Compare
+ assertArrayEquals("same binary content", expectedBin, outstr.toByteArray());
}
/**
- * Returns the file system manager used by this test.
+ * Builds the expected structure of the read tests folder.
+ *
+ * @throws FileSystemException (possibly)
*/
- protected DefaultFileSystemManager getManager() {
- return manager;
+ protected FileInfo buildExpectedStructure() throws FileSystemException {
+ // Build the expected structure
+ final FileInfo base = new FileInfo(getReadFolder().getName().getBaseName(), FileType.FOLDER);
+ base.addFile("file1.txt", FILE1_CONTENT);
+ // file%.txt - test out encoding
+ base.addFile("file%25.txt", FILE1_CONTENT);
+
+ // file?test.txt - test out encoding (test.txt is not the queryString)
+ // as we do not know if the current file provider we need to
+ // ask it to normalize the name
+ // todo: move this into the FileInfo class to do it generally?
+ /*
+ * webdav-bug?: didnt manage to get the "?" correctly through webdavlib FileSystemManager fsm =
+ * getReadFolder().getFileSystem().getFileSystemManager(); FileName fn =
+ * fsm.resolveName(getReadFolder().getName(), "file%3ftest.txt"); String baseName = fn.getBaseName();
+ * base.addFile(baseName, FILE1_CONTENT);
+ */
+ base.addFile("file space.txt", FILE1_CONTENT);
+
+ base.addFile("empty.txt", "");
+ if (addEmptyDir) {
+ base.addFolder("emptydir");
+ }
+
+ final FileInfo dir = base.addFolder("dir1");
+ dir.addFile("file1.txt", TEST_FILE_CONTENT);
+ dir.addFile("file2.txt", TEST_FILE_CONTENT);
+ dir.addFile("file3.txt", TEST_FILE_CONTENT);
+
+ final FileInfo subdir1 = dir.addFolder("subdir1");
+ subdir1.addFile("file1.txt", TEST_FILE_CONTENT);
+ subdir1.addFile("file2.txt", TEST_FILE_CONTENT);
+ subdir1.addFile("file3.txt", TEST_FILE_CONTENT);
+
+ final FileInfo subdir2 = dir.addFolder("subdir2");
+ subdir2.addFile("file1.txt", TEST_FILE_CONTENT);
+ subdir2.addFile("file2.txt", TEST_FILE_CONTENT);
+ subdir2.addFile("file3.txt", TEST_FILE_CONTENT);
+
+ final FileInfo subdir3 = dir.addFolder("subdir3");
+ subdir3.addFile("file1.txt", TEST_FILE_CONTENT);
+ subdir3.addFile("file2.txt", TEST_FILE_CONTENT);
+ subdir3.addFile("file3.txt", TEST_FILE_CONTENT);
+
+ final FileInfo subdir4 = dir.addFolder("subdir4.jar");
+ subdir4.addFile("file1.txt", TEST_FILE_CONTENT);
+ subdir4.addFile("file2.txt", TEST_FILE_CONTENT);
+ subdir4.addFile("file3.txt", TEST_FILE_CONTENT);
+
+ return base;
}
/**
@@ -100,6 +211,13 @@ public abstract class AbstractProviderTestCase extends AbstractVfsTestCase {
}
/**
+ * Returns the base test folder. This is the parent of both the read test and write test folders.
+ */
+ public FileObject getBaseFolder() {
+ return baseFolder;
+ }
+
+ /**
* some provider config do some post-initialization in getBaseTestFolder. This is a hack to allow access to this
* code for {@code createManager}
*/
@@ -114,10 +232,10 @@ public abstract class AbstractProviderTestCase extends AbstractVfsTestCase {
}
/**
- * Returns the base test folder. This is the parent of both the read test and write test folders.
+ * Returns the file system manager used by this test.
*/
- public FileObject getBaseFolder() {
- return baseFolder;
+ protected DefaultFileSystemManager getManager() {
+ return manager;
}
/**
@@ -135,22 +253,6 @@ public abstract class AbstractProviderTestCase extends AbstractVfsTestCase {
}
/**
- * Returns the write test folder.
- */
- protected FileObject getWriteFolder() {
- return writeFolder;
- }
-
- /**
- * Sets the write test folder.
- *
- * @param folder
- */
- protected void setWriteFolder(final FileObject folder) {
- writeFolder = folder;
- }
-
- /**
* Returns the capabilities required by the tests of this test case. The tests are not run if the provider being
* tested does not support all the required capabilities. Return null or an empty array to always run the tests.
* <p>
@@ -161,6 +263,13 @@ public abstract class AbstractProviderTestCase extends AbstractVfsTestCase {
}
/**
+ * Returns the write test folder.
+ */
+ protected FileObject getWriteFolder() {
+ return writeFolder;
+ }
+
+ /**
* Runs the test. This implementation short-circuits the test if the provider being tested does not have the
* capabilities required by this test.
* <p>
@@ -211,145 +320,36 @@ public abstract class AbstractProviderTestCase extends AbstractVfsTestCase {
}
/**
- * Asserts that the content of a file is the same as expected. Checks the length reported by getContentLength() is
- * correct, then reads the content as a byte stream and compares the result with the expected content. Assumes files
- * are encoded using UTF-8.
+ * Configures this test.
*/
- protected void assertSameURLContent(final String expected, final URLConnection connection) throws Exception {
- // Get file content as a binary stream
- final byte[] expectedBin = expected.getBytes(StandardCharsets.UTF_8);
-
- // Check lengths
- assertEquals("same content length", expectedBin.length, connection.getContentLength());
-
- // Read content into byte array
- final InputStream instr = connection.getInputStream();
- final ByteArrayOutputStream outstr;
- try {
- outstr = new ByteArrayOutputStream();
- final byte[] buffer = new byte[256];
- int nread = 0;
- while (nread >= 0) {
- outstr.write(buffer, 0, nread);
- nread = instr.read(buffer);
- }
- } finally {
- instr.close();
- }
-
- // Compare
- assertArrayEquals("same binary content", expectedBin, outstr.toByteArray());
+ public void setConfig(final DefaultFileSystemManager manager, final ProviderTestConfig providerConfig,
+ final FileObject baseFolder, final FileObject readFolder, final FileObject writeFolder) {
+ this.manager = manager;
+ this.providerConfig = providerConfig;
+ this.baseFolder = baseFolder;
+ this.readFolder = readFolder;
+ this.writeFolder = writeFolder;
+ assertNotNull("setConfig manager", manager);
+ assertNotNull("setConfig providerConfig", providerConfig);
+ assertNotNull("setConfig baseFolder", baseFolder);
+ assertNotNull("setConfig readFolder", readFolder);
+ assertNotNull("setConfig writeFolder", writeFolder);
}
/**
- * Asserts that the content of a file is the same as expected. Checks the length reported by getSize() is correct,
- * then reads the content as a byte stream and compares the result with the expected content. Assumes files are
- * encoded using UTF-8.
+ * Sets the test method.
*/
- protected void assertSameContent(final String expected, final FileObject file) throws Exception {
- // Check the file exists, and is a file
- assertTrue(file.exists());
- assertSame(FileType.FILE, file.getType());
- assertTrue(file.isFile());
-
- // Get file content as a binary stream
- final byte[] expectedBin = expected.getBytes(StandardCharsets.UTF_8);
-
- // Check lengths
- final FileContent content = file.getContent();
- assertEquals("same content length", expectedBin.length, content.getSize());
-
- // Read content into byte array
- final InputStream instr = content.getInputStream();
- final ByteArrayOutputStream outstr;
- try {
- outstr = new ByteArrayOutputStream(expectedBin.length);
- final byte[] buffer = new byte[256];
- int nread = 0;
- while (nread >= 0) {
- outstr.write(buffer, 0, nread);
- nread = instr.read(buffer);
- }
- } finally {
- instr.close();
- }
-
- // Compare
- assertArrayEquals("same binary content", expectedBin, outstr.toByteArray());
+ public void setMethod(final Method method) {
+ this.method = method;
}
/**
- * Builds the expected structure of the read tests folder.
+ * Sets the write test folder.
*
- * @throws FileSystemException (possibly)
+ * @param folder
*/
- protected FileInfo buildExpectedStructure() throws FileSystemException {
- // Build the expected structure
- final FileInfo base = new FileInfo(getReadFolder().getName().getBaseName(), FileType.FOLDER);
- base.addFile("file1.txt", FILE1_CONTENT);
- // file%.txt - test out encoding
- base.addFile("file%25.txt", FILE1_CONTENT);
-
- // file?test.txt - test out encoding (test.txt is not the queryString)
- // as we do not know if the current file provider we need to
- // ask it to normalize the name
- // todo: move this into the FileInfo class to do it generally?
- /*
- * webdav-bug?: didnt manage to get the "?" correctly through webdavlib FileSystemManager fsm =
- * getReadFolder().getFileSystem().getFileSystemManager(); FileName fn =
- * fsm.resolveName(getReadFolder().getName(), "file%3ftest.txt"); String baseName = fn.getBaseName();
- * base.addFile(baseName, FILE1_CONTENT);
- */
- base.addFile("file space.txt", FILE1_CONTENT);
-
- base.addFile("empty.txt", "");
- if (addEmptyDir) {
- base.addFolder("emptydir");
- }
-
- final FileInfo dir = base.addFolder("dir1");
- dir.addFile("file1.txt", TEST_FILE_CONTENT);
- dir.addFile("file2.txt", TEST_FILE_CONTENT);
- dir.addFile("file3.txt", TEST_FILE_CONTENT);
-
- final FileInfo subdir1 = dir.addFolder("subdir1");
- subdir1.addFile("file1.txt", TEST_FILE_CONTENT);
- subdir1.addFile("file2.txt", TEST_FILE_CONTENT);
- subdir1.addFile("file3.txt", TEST_FILE_CONTENT);
-
- final FileInfo subdir2 = dir.addFolder("subdir2");
- subdir2.addFile("file1.txt", TEST_FILE_CONTENT);
- subdir2.addFile("file2.txt", TEST_FILE_CONTENT);
- subdir2.addFile("file3.txt", TEST_FILE_CONTENT);
-
- final FileInfo subdir3 = dir.addFolder("subdir3");
- subdir3.addFile("file1.txt", TEST_FILE_CONTENT);
- subdir3.addFile("file2.txt", TEST_FILE_CONTENT);
- subdir3.addFile("file3.txt", TEST_FILE_CONTENT);
-
- final FileInfo subdir4 = dir.addFolder("subdir4.jar");
- subdir4.addFile("file1.txt", TEST_FILE_CONTENT);
- subdir4.addFile("file2.txt", TEST_FILE_CONTENT);
- subdir4.addFile("file3.txt", TEST_FILE_CONTENT);
-
- return base;
- }
-
- protected void addEmptyDir(final boolean addEmptyDir) {
- this.addEmptyDir = addEmptyDir;
- }
-
- protected static Test notConfigured(final Class<?> testClass) {
- return warning(testClass + " is not configured for tests, skipping");
- }
-
- private static Test warning(final String message) {
- return new TestCase("warning") {
- @Override
- protected void runTest() {
- System.out.println(message);
- }
- };
+ protected void setWriteFolder(final FileObject folder) {
+ writeFolder = folder;
}
@Override
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/AbstractTestSuite.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/AbstractTestSuite.java
index 5bb5250..038ec34 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/AbstractTestSuite.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/AbstractTestSuite.java
@@ -121,6 +121,108 @@ public abstract class AbstractTestSuite extends TestSetup {
}
}
+ /**
+ * Asserts that the temp dir is empty or gone.
+ */
+ private void checkTempDir(final String assertMsg) {
+ if (tempDir.exists()) {
+ Assert.assertTrue(assertMsg + " (" + tempDir.getAbsolutePath() + ")",
+ tempDir.isDirectory() && ArrayUtils.isEmpty(tempDir.list()));
+ }
+ }
+
+ private Thread[] createThreadSnapshot() {
+ ThreadGroup tg = Thread.currentThread().getThreadGroup();
+ while (tg.getParent() != null) {
+ tg = tg.getParent();
+ }
+
+ final Thread[] snapshot = new Thread[200];
+ tg.enumerate(snapshot, true);
+
+ return snapshot;
+ }
+
+ private Thread[] diffThreadSnapshot(final Thread[] startThreadSnapshot, final Thread[] endThreadSnapshot) {
+ final List<Thread> diff = new ArrayList<>(10);
+
+ nextEnd: for (final Thread element : endThreadSnapshot) {
+ for (final Thread element2 : startThreadSnapshot) {
+ if (element2 == element) {
+ continue nextEnd;
+ }
+ }
+
+ diff.add(element);
+ }
+
+ return diff.toArray(EMPTY_THREAD_ARRAY);
+ }
+
+ private String dumpThreadSnapshot(final Thread[] threadSnapshot) {
+ if (ArrayUtils.isEmpty(threadSnapshot)) {
+ return StringUtils.EMPTY;
+ }
+ final StringBuffer sb = new StringBuffer(256);
+ sb.append("Threads still running (" + threadSnapshot.length + ") at " + Instant.now() + ", live threads:");
+ sb.append(System.lineSeparator());
+
+ Field threadTargetField = null;
+ try {
+ threadTargetField = Thread.class.getDeclaredField("target");
+ threadTargetField.setAccessible(true);
+ } catch (final Exception e) {
+ System.err.println("Test suite cannot show you a thread snapshot: " + e);
+ }
+
+ int liveCount = 0;
+ for (int index = 0; index < threadSnapshot.length; index++) {
+ final Thread thread = threadSnapshot[index];
+ if (thread != null && thread.isAlive()) {
+ liveCount++;
+ sb.append("\tThread[");
+ sb.append(index);
+ sb.append("] ");
+ sb.append(" ID ");
+ sb.append(thread.getId());
+ sb.append(", ");
+ // prints [name,priority,group]
+ sb.append(thread);
+ sb.append(",\t");
+ sb.append(thread.getState());
+ sb.append(",\t");
+ if (!thread.isDaemon()) {
+ sb.append("non_");
+ }
+ sb.append("daemon");
+
+ if (threadTargetField != null) {
+ sb.append(",\t");
+ try {
+ final Object threadTarget = threadTargetField.get(thread);
+ if (threadTarget != null) {
+ sb.append(threadTarget.getClass().getCanonicalName());
+ } else {
+ sb.append("null");
+ }
+ } catch (final IllegalAccessException e) {
+ sb.append("unknown (");
+ sb.append(e);
+ sb.append(")");
+ }
+ }
+
+ sb.append(System.lineSeparator());
+// Stream.of(thread.getStackTrace()).forEach(e -> {
+// sb.append('\t');
+// sb.append(e);
+// sb.append(System.lineSeparator());
+// });
+ }
+ }
+ return liveCount == 0 ? StringUtils.EMPTY : sb.toString();
+ }
+
@Override
public void run(final TestResult result) {
final Protectable p = () -> {
@@ -226,106 +328,4 @@ public abstract class AbstractTestSuite extends TestSetup {
}
// System.in.read();
}
-
- /**
- * Asserts that the temp dir is empty or gone.
- */
- private void checkTempDir(final String assertMsg) {
- if (tempDir.exists()) {
- Assert.assertTrue(assertMsg + " (" + tempDir.getAbsolutePath() + ")",
- tempDir.isDirectory() && ArrayUtils.isEmpty(tempDir.list()));
- }
- }
-
- private String dumpThreadSnapshot(final Thread[] threadSnapshot) {
- if (ArrayUtils.isEmpty(threadSnapshot)) {
- return StringUtils.EMPTY;
- }
- final StringBuffer sb = new StringBuffer(256);
- sb.append("Threads still running (" + threadSnapshot.length + ") at " + Instant.now() + ", live threads:");
- sb.append(System.lineSeparator());
-
- Field threadTargetField = null;
- try {
- threadTargetField = Thread.class.getDeclaredField("target");
- threadTargetField.setAccessible(true);
- } catch (final Exception e) {
- System.err.println("Test suite cannot show you a thread snapshot: " + e);
- }
-
- int liveCount = 0;
- for (int index = 0; index < threadSnapshot.length; index++) {
- final Thread thread = threadSnapshot[index];
- if (thread != null && thread.isAlive()) {
- liveCount++;
- sb.append("\tThread[");
- sb.append(index);
- sb.append("] ");
- sb.append(" ID ");
- sb.append(thread.getId());
- sb.append(", ");
- // prints [name,priority,group]
- sb.append(thread);
- sb.append(",\t");
- sb.append(thread.getState());
- sb.append(",\t");
- if (!thread.isDaemon()) {
- sb.append("non_");
- }
- sb.append("daemon");
-
- if (threadTargetField != null) {
- sb.append(",\t");
- try {
- final Object threadTarget = threadTargetField.get(thread);
- if (threadTarget != null) {
- sb.append(threadTarget.getClass().getCanonicalName());
- } else {
- sb.append("null");
- }
- } catch (final IllegalAccessException e) {
- sb.append("unknown (");
- sb.append(e);
- sb.append(")");
- }
- }
-
- sb.append(System.lineSeparator());
-// Stream.of(thread.getStackTrace()).forEach(e -> {
-// sb.append('\t');
-// sb.append(e);
-// sb.append(System.lineSeparator());
-// });
- }
- }
- return liveCount == 0 ? StringUtils.EMPTY : sb.toString();
- }
-
- private Thread[] diffThreadSnapshot(final Thread[] startThreadSnapshot, final Thread[] endThreadSnapshot) {
- final List<Thread> diff = new ArrayList<>(10);
-
- nextEnd: for (final Thread element : endThreadSnapshot) {
- for (final Thread element2 : startThreadSnapshot) {
- if (element2 == element) {
- continue nextEnd;
- }
- }
-
- diff.add(element);
- }
-
- return diff.toArray(EMPTY_THREAD_ARRAY);
- }
-
- private Thread[] createThreadSnapshot() {
- ThreadGroup tg = Thread.currentThread().getThreadGroup();
- while (tg.getParent() != null) {
- tg = tg.getParent();
- }
-
- final Thread[] snapshot = new Thread[200];
- tg.enumerate(snapshot, true);
-
- return snapshot;
- }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/ContentTests.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/ContentTests.java
index 887dad5..53e5976 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/ContentTests.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/ContentTests.java
@@ -28,17 +28,6 @@ import org.junit.Test;
public class ContentTests extends AbstractProviderTestCase {
/**
- * Asserts that every expected file exists, and has the expected content.
- */
- @Test
- public void testAllContent() throws Exception {
- final FileInfo expectedFileInfo = buildExpectedStructure();
- final FileObject actualFolder = getReadFolder();
-
- assertSameContent(expectedFileInfo, actualFolder);
- }
-
- /**
* Asserts every file in a folder exists and has the expected content.
*/
private void assertSameContent(final FileInfo expected, final FileObject folder) throws Exception {
@@ -55,29 +44,14 @@ public class ContentTests extends AbstractProviderTestCase {
}
/**
- * Tests existence determination.
+ * Asserts that every expected file exists, and has the expected content.
*/
@Test
- public void testExists() throws Exception {
- // Test a file
- FileObject file = getReadFolder().resolveFile("file1.txt");
- assertTrue("file exists", file.exists());
- assertNotSame("file exists", file.getType(), FileType.IMAGINARY);
-
- // Test a folder
- file = getReadFolder().resolveFile("dir1");
- assertTrue("folder exists", file.exists());
- assertNotSame("folder exists", file.getType(), FileType.IMAGINARY);
-
- // Test an unknown file
- file = getReadFolder().resolveFile("unknown-child");
- assertFalse("unknown file does not exist", file.exists());
- assertSame("unknown file does not exist", file.getType(), FileType.IMAGINARY);
+ public void testAllContent() throws Exception {
+ final FileInfo expectedFileInfo = buildExpectedStructure();
+ final FileObject actualFolder = getReadFolder();
- // Test an unknown file in an unknown folder
- file = getReadFolder().resolveFile("unknown-folder/unknown-child");
- assertFalse("unknown file does not exist", file.exists());
- assertSame("unknown file does not exist", file.getType(), FileType.IMAGINARY);
+ assertSameContent(expectedFileInfo, actualFolder);
}
/**
@@ -89,69 +63,16 @@ public class ContentTests extends AbstractProviderTestCase {
}
/**
- * Tests root of file system exists.
- */
- @Test
- public void testRootURI() throws FileSystemException {
- if (!this.getProviderConfig().isFileSystemRootAccessible()) {
- return;
- }
- final FileSystem fileSystem = getFileSystem();
- final String uri = fileSystem.getRootURI();
- testRoot(getManager().resolveFile(uri, fileSystem.getFileSystemOptions()));
- }
-
- /**
- * Tests root of file system exists.
- */
- @Test
- public void testRootAPI() throws FileSystemException {
- if (!this.getProviderConfig().isFileSystemRootAccessible()) {
- return;
- }
- testRoot(getFileSystem().getRoot());
- }
-
- private void testRoot(final FileObject root) throws FileSystemException {
- assertTrue(root.exists());
- assertNotSame(root.getType(), FileType.IMAGINARY);
- }
-
- /**
- * Tests parent identity
+ * Tests that input streams are cleaned up on file close.
*/
@Test
- public void testParent() throws FileSystemException {
- // Test when both exist
- FileObject folder = getReadFolder().resolveFile("dir1");
- FileObject child = folder.resolveFile("file3.txt");
- assertTrue("folder exists", folder.exists());
- assertTrue("child exists", child.exists());
- assertSame(folder, child.getParent());
-
- // Test when file does not exist
- child = folder.resolveFile("unknown-file");
- assertTrue("folder exists", folder.exists());
- assertFalse("child does not exist", child.exists());
- assertSame(folder, child.getParent());
-
- // Test when neither exists
- folder = getReadFolder().resolveFile("unknown-folder");
- child = folder.resolveFile("unknown-file");
- assertFalse("folder does not exist", folder.exists());
- assertFalse("child does not exist", child.exists());
- assertSame(folder, child.getParent());
+ public void testByteArrayReadAll() throws Exception {
+ // Get the test file
+ try (final FileObject file = getReadFolder().resolveFile("file1.txt")) {
+ assertEquals(FileType.FILE, file.getType());
+ assertTrue(file.isFile());
- // Test the parent of the root of the file system
- // TODO - refactor out test cases for layered vs originating fs
- final FileSystem fileSystem = getFileSystem();
- final FileObject root = fileSystem.getRoot();
- if (fileSystem.getParentLayer() == null) {
- // No parent layer, so parent should be null
- assertNull("root has null parent", root.getParent());
- } else {
- // Parent should be parent of parent layer.
- assertSame(fileSystem.getParentLayer().getParent(), root.getParent());
+ assertEquals(FILE1_CONTENT, new String(file.getContent().getByteArray()));
}
}
@@ -205,94 +126,51 @@ public class ContentTests extends AbstractProviderTestCase {
}
/**
- * Tests that unknown files have no content.
- */
- @Test
- public void testUnknownContent() throws Exception {
-
- // Try getting the content of an unknown file
- final FileObject unknownFile = getReadFolder().resolveFile("unknown-file");
- final FileContent content = unknownFile.getContent();
- try {
- content.getInputStream();
- fail();
- } catch (final FileSystemException e) {
- assertSameMessage("vfs.provider/read-not-file.error", unknownFile, e);
- }
- try {
- content.getSize();
- fail();
- } catch (final FileSystemException e) {
- assertSameMessage("vfs.provider/get-size-not-file.error", unknownFile, e);
- }
- }
-
- /**
- * Tests concurrent reads on a file.
+ * Tests existence determination.
*/
@Test
- public void testReadSingleSequencial() throws Exception {
- final FileObject file = getReadFolder().resolveFile("file1.txt");
- assertTrue(file.exists());
+ public void testExists() throws Exception {
+ // Test a file
+ FileObject file = getReadFolder().resolveFile("file1.txt");
+ assertTrue("file exists", file.exists());
+ assertNotSame("file exists", file.getType(), FileType.IMAGINARY);
- file.getContent().getInputStream().close();
- file.getContent().getInputStream().close();
- }
+ // Test a folder
+ file = getReadFolder().resolveFile("dir1");
+ assertTrue("folder exists", file.exists());
+ assertNotSame("folder exists", file.getType(), FileType.IMAGINARY);
- /**
- * Tests concurrent reads on a file.
- */
- @Test
- public void testReadSingleConcurrent() throws Exception {
- final FileObject file = getReadFolder().resolveFile("file1.txt");
- assertTrue(file.exists());
+ // Test an unknown file
+ file = getReadFolder().resolveFile("unknown-child");
+ assertFalse("unknown file does not exist", file.exists());
+ assertSame("unknown file does not exist", file.getType(), FileType.IMAGINARY);
- // Start reading from the file
- try (InputStream instr = file.getContent().getInputStream()) {
- // Start reading again
- file.getContent().getInputStream().close();
- }
+ // Test an unknown file in an unknown folder
+ file = getReadFolder().resolveFile("unknown-folder/unknown-child");
+ assertFalse("unknown file does not exist", file.exists());
+ assertSame("unknown file does not exist", file.getType(), FileType.IMAGINARY);
}
- /**
- * Tests concurrent reads on different files works.
- */
@Test
- public void testReadMultipleConcurrent() throws Exception {
- final FileObject file = getReadFolder().resolveFile("file1.txt");
- assertTrue(file.exists());
- final FileObject emptyFile = getReadFolder().resolveFile("empty.txt");
- assertTrue(emptyFile.exists());
+ public void testGetString_Charset() throws Exception {
+ // Get the test file
+ try (final FileObject file = getReadFolder().resolveFile("file1.txt")) {
+ assertEquals(FileType.FILE, file.getType());
+ assertTrue(file.isFile());
- // Start reading from the file
- try (InputStream instr = file.getContent().getInputStream()) {
- // Try to read from other file
- assertSameContent("", emptyFile);
+ assertEquals(FILE1_CONTENT, new String(file.getContent().getString(StandardCharsets.UTF_8)));
}
}
- /**
- * Tests that content and file objects are usable after being closed.
- */
@Test
- public void testReuse() throws Exception {
+ public void testGetString_String() throws Exception {
// Get the test file
- final FileObject file = getReadFolder().resolveFile("file1.txt");
- assertEquals(FileType.FILE, file.getType());
- assertTrue(file.isFile());
-
- // Get the file content
- assertSameContent(FILE1_CONTENT, file);
-
- // Read the content again
- assertSameContent(FILE1_CONTENT, file);
-
- // Close the content + file
- file.getContent().close();
- file.close();
+ try (final FileObject file = getReadFolder().resolveFile("file1.txt")) {
+ assertEquals(FileType.FILE, file.getType());
+ assertTrue(file.isFile());
- // Read the content again
- assertSameContent(FILE1_CONTENT, file);
+ assertEquals(FILE1_CONTENT, new String(file.getContent().getString(StandardCharsets.UTF_8.name())));
+ }
}
/**
@@ -323,6 +201,22 @@ public class ContentTests extends AbstractProviderTestCase {
* Tests that input streams are cleaned up on file close.
*/
@Test
+ public void testInputStreamReadAll() throws Exception {
+ // Get the test file
+ try (final FileObject file = getReadFolder().resolveFile("file1.txt")) {
+ assertEquals(FileType.FILE, file.getType());
+ assertTrue(file.isFile());
+
+ final ByteArrayOutputStream output = new ByteArrayOutputStream();
+ file.getContent().write(output);
+ assertEquals(FILE1_CONTENT, new String(output.toByteArray()));
+ }
+ }
+
+ /**
+ * Tests that input streams are cleaned up on file close.
+ */
+ @Test
public void testInputStreamSingleCleanup() throws Exception {
// Get the test file
final FileObject file = getReadFolder().resolveFile("file1.txt");
@@ -341,54 +235,160 @@ public class ContentTests extends AbstractProviderTestCase {
}
/**
- * Tests that input streams are cleaned up on file close.
+ * Tests parent identity
*/
@Test
- public void testInputStreamReadAll() throws Exception {
- // Get the test file
- try (final FileObject file = getReadFolder().resolveFile("file1.txt")) {
- assertEquals(FileType.FILE, file.getType());
- assertTrue(file.isFile());
+ public void testParent() throws FileSystemException {
+ // Test when both exist
+ FileObject folder = getReadFolder().resolveFile("dir1");
+ FileObject child = folder.resolveFile("file3.txt");
+ assertTrue("folder exists", folder.exists());
+ assertTrue("child exists", child.exists());
+ assertSame(folder, child.getParent());
- final ByteArrayOutputStream output = new ByteArrayOutputStream();
- file.getContent().write(output);
- assertEquals(FILE1_CONTENT, new String(output.toByteArray()));
+ // Test when file does not exist
+ child = folder.resolveFile("unknown-file");
+ assertTrue("folder exists", folder.exists());
+ assertFalse("child does not exist", child.exists());
+ assertSame(folder, child.getParent());
+
+ // Test when neither exists
+ folder = getReadFolder().resolveFile("unknown-folder");
+ child = folder.resolveFile("unknown-file");
+ assertFalse("folder does not exist", folder.exists());
+ assertFalse("child does not exist", child.exists());
+ assertSame(folder, child.getParent());
+
+ // Test the parent of the root of the file system
+ // TODO - refactor out test cases for layered vs originating fs
+ final FileSystem fileSystem = getFileSystem();
+ final FileObject root = fileSystem.getRoot();
+ if (fileSystem.getParentLayer() == null) {
+ // No parent layer, so parent should be null
+ assertNull("root has null parent", root.getParent());
+ } else {
+ // Parent should be parent of parent layer.
+ assertSame(fileSystem.getParentLayer().getParent(), root.getParent());
}
}
/**
- * Tests that input streams are cleaned up on file close.
+ * Tests concurrent reads on different files works.
*/
@Test
- public void testByteArrayReadAll() throws Exception {
- // Get the test file
- try (final FileObject file = getReadFolder().resolveFile("file1.txt")) {
- assertEquals(FileType.FILE, file.getType());
- assertTrue(file.isFile());
+ public void testReadMultipleConcurrent() throws Exception {
+ final FileObject file = getReadFolder().resolveFile("file1.txt");
+ assertTrue(file.exists());
+ final FileObject emptyFile = getReadFolder().resolveFile("empty.txt");
+ assertTrue(emptyFile.exists());
- assertEquals(FILE1_CONTENT, new String(file.getContent().getByteArray()));
+ // Start reading from the file
+ try (InputStream instr = file.getContent().getInputStream()) {
+ // Try to read from other file
+ assertSameContent("", emptyFile);
}
}
+ /**
+ * Tests concurrent reads on a file.
+ */
@Test
- public void testGetString_Charset() throws Exception {
- // Get the test file
- try (final FileObject file = getReadFolder().resolveFile("file1.txt")) {
- assertEquals(FileType.FILE, file.getType());
- assertTrue(file.isFile());
+ public void testReadSingleConcurrent() throws Exception {
+ final FileObject file = getReadFolder().resolveFile("file1.txt");
+ assertTrue(file.exists());
- assertEquals(FILE1_CONTENT, new String(file.getContent().getString(StandardCharsets.UTF_8)));
+ // Start reading from the file
+ try (InputStream instr = file.getContent().getInputStream()) {
+ // Start reading again
+ file.getContent().getInputStream().close();
}
}
+ /**
+ * Tests concurrent reads on a file.
+ */
@Test
- public void testGetString_String() throws Exception {
+ public void testReadSingleSequencial() throws Exception {
+ final FileObject file = getReadFolder().resolveFile("file1.txt");
+ assertTrue(file.exists());
+
+ file.getContent().getInputStream().close();
+ file.getContent().getInputStream().close();
+ }
+
+ /**
+ * Tests that content and file objects are usable after being closed.
+ */
+ @Test
+ public void testReuse() throws Exception {
// Get the test file
- try (final FileObject file = getReadFolder().resolveFile("file1.txt")) {
- assertEquals(FileType.FILE, file.getType());
- assertTrue(file.isFile());
+ final FileObject file = getReadFolder().resolveFile("file1.txt");
+ assertEquals(FileType.FILE, file.getType());
+ assertTrue(file.isFile());
- assertEquals(FILE1_CONTENT, new String(file.getContent().getString(StandardCharsets.UTF_8.name())));
+ // Get the file content
+ assertSameContent(FILE1_CONTENT, file);
+
+ // Read the content again
+ assertSameContent(FILE1_CONTENT, file);
+
+ // Close the content + file
+ file.getContent().close();
+ file.close();
+
+ // Read the content again
+ assertSameContent(FILE1_CONTENT, file);
+ }
+
+ private void testRoot(final FileObject root) throws FileSystemException {
+ assertTrue(root.exists());
+ assertNotSame(root.getType(), FileType.IMAGINARY);
+ }
+
+ /**
+ * Tests root of file system exists.
+ */
+ @Test
+ public void testRootAPI() throws FileSystemException {
+ if (!this.getProviderConfig().isFileSystemRootAccessible()) {
+ return;
+ }
+ testRoot(getFileSystem().getRoot());
+ }
+
+ /**
+ * Tests root of file system exists.
+ */
+ @Test
+ public void testRootURI() throws FileSystemException {
+ if (!this.getProviderConfig().isFileSystemRootAccessible()) {
+ return;
+ }
+ final FileSystem fileSystem = getFileSystem();
+ final String uri = fileSystem.getRootURI();
+ testRoot(getManager().resolveFile(uri, fileSystem.getFileSystemOptions()));
+ }
+
+ /**
+ * Tests that unknown files have no content.
+ */
+ @Test
+ public void testUnknownContent() throws Exception {
+
+ // Try getting the content of an unknown file
+ final FileObject unknownFile = getReadFolder().resolveFile("unknown-file");
+ final FileContent content = unknownFile.getContent();
+ try {
+ content.getInputStream();
+ fail();
+ } catch (final FileSystemException e) {
+ assertSameMessage("vfs.provider/read-not-file.error", unknownFile, e);
+ }
+ try {
+ content.getSize();
+ fail();
+ } catch (final FileSystemException e) {
+ assertSameMessage("vfs.provider/get-size-not-file.error", unknownFile, e);
}
}
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/FileInfo.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/FileInfo.java
index 240188b..4f7c1af 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/FileInfo.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/FileInfo.java
@@ -42,10 +42,6 @@ public class FileInfo {
this.content = content;
}
- public FileInfo getParent() {
- return parent;
- }
-
/**
* Adds a child.
*/
@@ -82,12 +78,11 @@ public class FileInfo {
}
/**
- * Returns the {@link FileType} of the file
- *
- * @return {@link FileType}
+ * Returns a {@code Map} of this {@code FileInfo}'s children.
+ * @return the {@code FileInfo}'s children
*/
- public FileType getType() {
- return type;
+ public Map<String, FileInfo> getChildren() {
+ return children;
}
/**
@@ -99,11 +94,16 @@ public class FileInfo {
return content;
}
+ public FileInfo getParent() {
+ return parent;
+ }
+
/**
- * Returns a {@code Map} of this {@code FileInfo}'s children.
- * @return the {@code FileInfo}'s children
+ * Returns the {@link FileType} of the file
+ *
+ * @return {@link FileType}
*/
- public Map<String, FileInfo> getChildren() {
- return children;
+ public FileType getType() {
+ return type;
}
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/FileSystemExceptionTest.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/FileSystemExceptionTest.java
index 9bfa8b2..3bbf8ad 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/FileSystemExceptionTest.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/FileSystemExceptionTest.java
@@ -25,6 +25,16 @@ import org.junit.Test;
*/
public class FileSystemExceptionTest {
/**
+ * Tests a {@link FileSystemException} containing info with a URL containing only the user information.
+ */
+ @Test
+ public void testDoesNotModifyUrlsWithoutPassword() {
+ final FileSystemException fse = new FileSystemException("vfs.provider/delete.error",
+ "http://foo@junit.org/test.bin");
+ assertEquals("http://foo@junit.org/test.bin", fse.getInfo()[0]);
+ }
+
+ /**
* Tests a {@link FileSystemException} containing info with a URL containing a complete basic authentication.
*/
@Test
@@ -37,16 +47,6 @@ public class FileSystemExceptionTest {
}
/**
- * Tests a {@link FileSystemException} containing info with a URL containing only the user information.
- */
- @Test
- public void testDoesNotModifyUrlsWithoutPassword() {
- final FileSystemException fse = new FileSystemException("vfs.provider/delete.error",
- "http://foo@junit.org/test.bin");
- assertEquals("http://foo@junit.org/test.bin", fse.getInfo()[0]);
- }
-
- /**
* Tests a {@link FileSystemException} containing info with a nested URL containing a complete basic authentication.
*/
@Test
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/FileSystemManagerFactoryTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/FileSystemManagerFactoryTestCase.java
index 1f9616e..4533665 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/FileSystemManagerFactoryTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/FileSystemManagerFactoryTestCase.java
@@ -25,6 +25,20 @@ import org.junit.Test;
*/
public class FileSystemManagerFactoryTestCase extends AbstractVfsTestCase {
+ private void check(final FileSystemManager manager, FileObject file) throws FileSystemException {
+ assertNotNull(file);
+ assertTrue(file.exists());
+ assertSame(FileType.FILE, file.getType());
+ assertTrue(file.isFile());
+
+ // Expand it
+ file = manager.createFileSystem(file);
+ assertNotNull(file);
+ assertTrue(file.exists());
+ assertSame(FileType.FOLDER, file.getType());
+ assertTrue(file.isFolder());
+ }
+
/**
* Sanity test.
*/
@@ -46,18 +60,4 @@ public class FileSystemManagerFactoryTestCase extends AbstractVfsTestCase {
check(manager, file3);
}
- private void check(final FileSystemManager manager, FileObject file) throws FileSystemException {
- assertNotNull(file);
- assertTrue(file.exists());
- assertSame(FileType.FILE, file.getType());
- assertTrue(file.isFile());
-
- // Expand it
- file = manager.createFileSystem(file);
- assertNotNull(file);
- assertTrue(file.exists());
- assertSame(FileType.FOLDER, file.getType());
- assertTrue(file.isFolder());
- }
-
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/FileSystemOptionsTest.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/FileSystemOptionsTest.java
index a2870e4..47ed535 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/FileSystemOptionsTest.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/FileSystemOptionsTest.java
@@ -26,6 +26,30 @@ import org.junit.Test;
*/
public class FileSystemOptionsTest {
+ public static class JUnitConfigBuilder extends FileSystemConfigBuilder {
+ private abstract static class JUnitFS implements FileSystem {
+ }
+
+ private static final JUnitConfigBuilder BUILDER = new JUnitConfigBuilder();
+
+ public static JUnitConfigBuilder getInstance() {
+ return BUILDER;
+ }
+
+ @Override
+ protected Class<? extends FileSystem> getConfigClass() {
+ return JUnitFS.class;
+ }
+
+ public void setId(final FileSystemOptions opts, final String id) {
+ setParam(opts, "id", id);
+ }
+
+ public void setNames(final FileSystemOptions opts, final String[] names) {
+ setParam(opts, "names", names);
+ }
+ }
+
@Test
public void testEqualsHashCodeAndCompareTo() {
final JUnitConfigBuilder builder = JUnitConfigBuilder.getInstance();
@@ -52,28 +76,4 @@ public class FileSystemOptionsTest {
Assert.assertEquals(expected.hashCode(), actual.hashCode());
}
- public static class JUnitConfigBuilder extends FileSystemConfigBuilder {
- private static final JUnitConfigBuilder BUILDER = new JUnitConfigBuilder();
-
- public static JUnitConfigBuilder getInstance() {
- return BUILDER;
- }
-
- public void setId(final FileSystemOptions opts, final String id) {
- setParam(opts, "id", id);
- }
-
- public void setNames(final FileSystemOptions opts, final String[] names) {
- setParam(opts, "names", names);
- }
-
- @Override
- protected Class<? extends FileSystem> getConfigClass() {
- return JUnitFS.class;
- }
-
- private abstract static class JUnitFS implements FileSystem {
- }
- }
-
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/FileTypeTest.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/FileTypeTest.java
index e269670..f3b6ce3 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/FileTypeTest.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/FileTypeTest.java
@@ -39,9 +39,17 @@ public class FileTypeTest {
}
- @Test
- public void testSerializationFile() {
- test(FileType.FILE);
+ private void assertEquals(final FileType expected, final FileType actualFileType) {
+ Assert.assertEquals(expected.getName(), actualFileType.getName());
+ Assert.assertEquals(expected.hasAttributes(), actualFileType.hasAttributes());
+ Assert.assertEquals(expected.hasChildren(), actualFileType.hasChildren());
+ Assert.assertEquals(expected.hasContent(), actualFileType.hasContent());
+ }
+
+ private void test(final FileType expected) {
+ final byte[] serialized = SerializationUtils.serialize(expected);
+ final FileType actualFileType = (FileType) SerializationUtils.deserialize(serialized);
+ assertEquals(expected, actualFileType);
}
@Test
@@ -53,6 +61,11 @@ public class FileTypeTest {
}
@Test
+ public void testSerializationFile() {
+ test(FileType.FILE);
+ }
+
+ @Test
public void testSerializationFileOrFolder() {
test(FileType.FILE_OR_FOLDER);
}
@@ -66,17 +79,4 @@ public class FileTypeTest {
public void testSerializationImaginary() {
test(FileType.IMAGINARY);
}
-
- private void test(final FileType expected) {
- final byte[] serialized = SerializationUtils.serialize(expected);
- final FileType actualFileType = (FileType) SerializationUtils.deserialize(serialized);
- assertEquals(expected, actualFileType);
- }
-
- private void assertEquals(final FileType expected, final FileType actualFileType) {
- Assert.assertEquals(expected.getName(), actualFileType.getName());
- Assert.assertEquals(expected.hasAttributes(), actualFileType.hasAttributes());
- Assert.assertEquals(expected.hasChildren(), actualFileType.hasChildren());
- Assert.assertEquals(expected.hasContent(), actualFileType.hasContent());
- }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/LastModifiedTests.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/LastModifiedTests.java
index 65a22f0..7b5f72c 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/LastModifiedTests.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/LastModifiedTests.java
@@ -79,65 +79,65 @@ public class LastModifiedTests extends AbstractProviderTestCase {
}
/**
- * Tests getting the last modified time of a folder.
+ * Tests getting the last modified time of a file.
*
* @throws FileSystemException if error occurred
*/
@Test
- public void testGetLastModifiedFolder() throws FileSystemException {
- final FileObject file = getReadFolder().resolveFile("dir1");
+ public void testGetLastModifiedFile() throws FileSystemException {
+ final FileObject file = getReadFolder().resolveFile("file1.txt");
assertNotEquals(0L, file.getContent().getLastModifiedTime());
}
/**
- * Tests getting the last modified time of a file.
+ * Tests getting the last modified time of a folder.
*
* @throws FileSystemException if error occurred
*/
@Test
- public void testGetLastModifiedFile() throws FileSystemException {
- final FileObject file = getReadFolder().resolveFile("file1.txt");
+ public void testGetLastModifiedFolder() throws FileSystemException {
+ final FileObject file = getReadFolder().resolveFile("dir1");
assertNotEquals(0L, file.getContent().getLastModifiedTime());
}
/**
- * Tests setting the last modified time of a folder.
+ * Tests setting the last modified time of file.
*
* @throws FileSystemException if error occurred
*/
@Test
- public void testSetLastModifiedFolder() throws FileSystemException {
+ public void testSetLastModifiedFile() throws FileSystemException {
final long yesterdayMillis = Instant.now().minus(ONE_DAY).toEpochMilli();
- if (getReadFolder().getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FOLDER)) {
- // Try a folder
- final FileObject folder = getReadFolder().resolveFile("dir1");
- folder.getContent().setLastModifiedTime(yesterdayMillis);
- final long lastModTimeAccuracyMillis = (long) folder.getFileSystem().getLastModTimeAccuracy();
+ if (getReadFolder().getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FILE)) {
+ // Try a file
+ final FileObject file = getReadFolder().resolveFile("file1.txt");
+ file.getContent().setLastModifiedTime(yesterdayMillis);
+ final long lastModTimeAccuracyMillis = (long) file.getFileSystem().getLastModTimeAccuracy();
// folder.refresh(); TODO: does not work with SSH VFS-563
- final long lastModifiedTime = folder.getContent().getLastModifiedTime();
- assertDeltaMillis("set/getLastModified on Folder", yesterdayMillis, lastModifiedTime,
+ final long lastModifiedTime = file.getContent().getLastModifiedTime();
+ assertDeltaMillis("set/getLastModified on File", yesterdayMillis, lastModifiedTime,
lastModTimeAccuracyMillis);
}
}
/**
- * Tests setting the last modified time of file.
+ * Tests setting the last modified time of a folder.
*
* @throws FileSystemException if error occurred
*/
@Test
- public void testSetLastModifiedFile() throws FileSystemException {
+ public void testSetLastModifiedFolder() throws FileSystemException {
final long yesterdayMillis = Instant.now().minus(ONE_DAY).toEpochMilli();
- if (getReadFolder().getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FILE)) {
- // Try a file
- final FileObject file = getReadFolder().resolveFile("file1.txt");
- file.getContent().setLastModifiedTime(yesterdayMillis);
- final long lastModTimeAccuracyMillis = (long) file.getFileSystem().getLastModTimeAccuracy();
+ if (getReadFolder().getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FOLDER)) {
+ // Try a folder
+ final FileObject folder = getReadFolder().resolveFile("dir1");
+ folder.getContent().setLastModifiedTime(yesterdayMillis);
+ final long lastModTimeAccuracyMillis = (long) folder.getFileSystem().getLastModTimeAccuracy();
// folder.refresh(); TODO: does not work with SSH VFS-563
- final long lastModifiedTime = file.getContent().getLastModifiedTime();
- assertDeltaMillis("set/getLastModified on File", yesterdayMillis, lastModifiedTime,
+ final long lastModifiedTime = folder.getContent().getLastModifiedTime();
+ assertDeltaMillis("set/getLastModified on Folder", yesterdayMillis, lastModifiedTime,
lastModTimeAccuracyMillis);
}
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/NamingTests.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/NamingTests.java
index 63b09c3..820b3f2 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/NamingTests.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/NamingTests.java
@@ -26,137 +26,66 @@ import org.junit.Test;
public class NamingTests extends AbstractProviderTestCase {
/**
- * Tests resolution of relative file names via the FS manager
- */
- @Test
- public void testRelativeURI() throws Exception {
- // Build base dir
- getManager().setBaseFile(getReadFolder());
-
- // Locate the base dir
- FileObject file = getManager().resolveFile(".");
- assertSame("file object", getReadFolder(), file);
-
- // Locate a child
- file = getManager().resolveFile("some-child");
- assertSame("file object", getReadFolder(), file.getParent());
-
- // Locate a descendent
- file = getManager().resolveFile("some-folder/some-file");
- assertSame("file object", getReadFolder(), file.getParent().getParent());
-
- // Locate parent
- file = getManager().resolveFile("..");
- assertSame("file object", getReadFolder().getParent(), file);
-
- // free basefile
- getManager().setBaseFile((FileObject) null);
- }
-
- /**
- * Tests encoding of relative URI.
+ * Asserts that a particular relative name is invalid for a particular scope.
*/
- @Test
- public void testRelativeUriEncoding() throws Exception {
- // Build base dir
- getManager().setBaseFile(getReadFolder());
- final String path = getReadFolder().getName().getPath();
-
- // §1 Encode "some file"
- FileObject file = getManager().resolveFile("%73%6f%6d%65%20%66%69%6c%65");
- assertEquals(path + "/some file", file.getName().getPathDecoded());
-
- // §2 Encode "."
- file = getManager().resolveFile("%2e");
- // 18-6-2005 imario@apache.org: no need to keep the "current directory"
- // assertEquals(path + "/.", file.getName().getPathDecoded());
- assertEquals(path, file.getName().getPathDecoded());
-
- // §3 Encode '%'
- file = getManager().resolveFile("a%25");
- assertEquals(path + "/a%", file.getName().getPathDecoded());
-
- // §4 Encode /
- file = getManager().resolveFile("dir%2fchild");
- assertEquals(path + "/dir/child", file.getName().getPathDecoded());
-
- // §5 Encode \
- file = getManager().resolveFile("dir%5cchild");
- // 18-6-2005 imario@apache.org: all file separators normalized to "/"
- // decided to do this to get the same behavior as in §4 on windows
- // platforms
- // assertEquals(path + "/dir\\child", file.getName().getPathDecoded());
- assertEquals(path + "/dir/child", file.getName().getPathDecoded());
-
- // §6 Use "%" literal
- try {
- getManager().resolveFile("%");
- fail();
- } catch (final FileSystemException e) {
- }
-
- // §7 Not enough digits in encoded char
- try {
- getManager().resolveFile("%5");
- fail();
- } catch (final FileSystemException e) {
- }
-
- // §8 Invalid digit in encoded char
+ private void assertBadName(final FileName name, final String relName, final NameScope scope) {
try {
- getManager().resolveFile("%q");
- fail();
+ getManager().resolveName(name, relName, scope);
+ fail("expected failure");
} catch (final FileSystemException e) {
+ // TODO - should check error message
}
-
- // free basefile
- getManager().setBaseFile((FileObject) null);
}
/**
- * Tests the root file name.
+ * Checks that a relative name resolves to the expected absolute path. Tests both forward and back slashes.
*/
- @Test
- public void testRootFileName() throws Exception {
- // Locate the root file
- final FileName rootName = getReadFolder().getFileSystem().getRoot().getName();
-
- // Test that the root path is "/"
- assertEquals("root path", "/", rootName.getPath());
-
- // Test that the root basname is ""
- assertEquals("root base name", "", rootName.getBaseName());
-
- // Test that the root name has no parent
- assertNull("root parent", rootName.getParent());
+ private void assertSameName(final String expectedPath, final FileName baseName, final String relName)
+ throws Exception {
+ assertSameName(expectedPath, baseName, relName, NameScope.FILE_SYSTEM);
}
/**
- * Tests child file names.
+ * Checks that a relative name resolves to the expected absolute path. Tests both forward and back slashes.
*/
- @Test
- public void testChildName() throws Exception {
- final FileName baseName = getReadFolder().getName();
- final String basePath = baseName.getPath();
- final FileName name = getManager().resolveName(baseName, "some-child", NameScope.CHILD);
+ private void assertSameName(final String expectedPath, final FileName baseName, final String relName,
+ final NameScope scope) throws Exception {
+ // Try the supplied name
+ FileName name = getManager().resolveName(baseName, relName, scope);
+ assertEquals(expectedPath, name.getPath());
- // Test path is absolute
- assertTrue("is absolute", basePath.startsWith("/"));
+ String temp;
- // Test base name
- assertEquals("base name", "some-child", name.getBaseName());
+ // Replace the separators
+ temp = relName.replace('\\', '/');
+ name = getManager().resolveName(baseName, temp, scope);
+ assertEquals(expectedPath, name.getPath());
- // Test absolute path
- assertEquals("absolute path", basePath + "/some-child", name.getPath());
+ // And again
+ temp = relName.replace('/', '\\');
+ name = getManager().resolveName(baseName, temp, scope);
+ assertEquals(expectedPath, name.getPath());
+ }
- // Test parent path
- assertEquals("parent absolute path", basePath, name.getParent().getPath());
+ /**
+ * Tests resolution of absolute names.
+ */
+ private void checkAbsoluteNames(final FileName name) throws Exception {
+ // Root
+ assertSameName("/", name, "/");
+ assertSameName("/", name, "//");
+ assertSameName("/", name, "/.");
+ assertSameName("/", name, "/some file/..");
- // Try using a compound name to find a child
- assertBadName(name, "a/b", NameScope.CHILD);
+ // Some absolute names
+ assertSameName("/a", name, "/a");
+ assertSameName("/a", name, "/./a");
+ assertSameName("/a", name, "/a/.");
+ assertSameName("/a/b", name, "/a/b");
- // Check other invalid names
- checkDescendentNames(name, NameScope.CHILD);
+ // Some bad names
+ assertBadName(name, "/..", NameScope.FILE_SYSTEM);
+ assertBadName(name, "/a/../..", NameScope.FILE_SYSTEM);
}
/**
@@ -195,33 +124,123 @@ public class NamingTests extends AbstractProviderTestCase {
}
/**
- * Checks that a relative name resolves to the expected absolute path. Tests both forward and back slashes.
+ * Tests conversion from absolute to relative names.
*/
- private void assertSameName(final String expectedPath, final FileName baseName, final String relName,
- final NameScope scope) throws Exception {
- // Try the supplied name
- FileName name = getManager().resolveName(baseName, relName, scope);
- assertEquals(expectedPath, name.getPath());
+ @Test
+ public void testAbsoluteNameConvert() throws Exception {
+ final FileName baseName = getReadFolder().getName();
- String temp;
+ String path = "/test1/test2";
+ FileName name = getManager().resolveName(baseName, path);
+ assertEquals(path, name.getPath());
- // Replace the separators
- temp = relName.replace('\\', '/');
- name = getManager().resolveName(baseName, temp, scope);
- assertEquals(expectedPath, name.getPath());
+ // Try child and descendent names
+ testRelName(name, "child");
+ testRelName(name, "child1/child2");
- // And again
- temp = relName.replace('/', '\\');
- name = getManager().resolveName(baseName, temp, scope);
- assertEquals(expectedPath, name.getPath());
+ // Try own name
+ testRelName(name, ".");
+
+ // Try parent, and root
+ testRelName(name, "..");
+ testRelName(name, "../..");
+
+ // Try sibling and descendent of sibling
+ testRelName(name, "../sibling");
+ testRelName(name, "../sibling/child");
+
+ // Try siblings with similar names
+ testRelName(name, "../test2_not");
+ testRelName(name, "../test2_not/child");
+ testRelName(name, "../test");
+ testRelName(name, "../test/child");
+
+ // Try unrelated
+ testRelName(name, "../../unrelated");
+ testRelName(name, "../../test");
+ testRelName(name, "../../test/child");
+
+ // Test against root
+ path = "/";
+ name = getManager().resolveName(baseName, path);
+ assertEquals(path, name.getPath());
+
+ // Try child and descendent names (against root)
+ testRelName(name, "child");
+ testRelName(name, "child1/child2");
+
+ // Try own name (against root)
+ testRelName(name, ".");
}
/**
- * Checks that a relative name resolves to the expected absolute path. Tests both forward and back slashes.
+ * Tests resolution of absolute names.
*/
- private void assertSameName(final String expectedPath, final FileName baseName, final String relName)
- throws Exception {
- assertSameName(expectedPath, baseName, relName, NameScope.FILE_SYSTEM);
+ @Test
+ public void testAbsoluteNames() throws Exception {
+ // Test against the base folder
+ FileName name = getReadFolder().getName();
+ checkAbsoluteNames(name);
+
+ // Test against the root
+ name = getReadFolder().getFileSystem().getRoot().getName();
+ checkAbsoluteNames(name);
+
+ // Test against some unknown file
+ name = getManager().resolveName(name, "a/b/unknown");
+ checkAbsoluteNames(name);
+ }
+
+ /**
+ * Tests child file names.
+ */
+ @Test
+ public void testChildName() throws Exception {
+ final FileName baseName = getReadFolder().getName();
+ final String basePath = baseName.getPath();
+ final FileName name = getManager().resolveName(baseName, "some-child", NameScope.CHILD);
+
+ // Test path is absolute
+ assertTrue("is absolute", basePath.startsWith("/"));
+
+ // Test base name
+ assertEquals("base name", "some-child", name.getBaseName());
+
+ // Test absolute path
+ assertEquals("absolute path", basePath + "/some-child", name.getPath());
+
+ // Test parent path
+ assertEquals("parent absolute path", basePath, name.getParent().getPath());
+
+ // Try using a compound name to find a child
+ assertBadName(name, "a/b", NameScope.CHILD);
+
+ // Check other invalid names
+ checkDescendentNames(name, NameScope.CHILD);
+ }
+
+ /**
+ * Tests descendent name resolution.
+ */
+ @Test
+ public void testDescendentName() throws Exception {
+ final FileName baseName = getReadFolder().getName();
+
+ // Test direct child
+ String path = baseName.getPath() + "/some-child";
+ assertSameName(path, baseName, "some-child", NameScope.DESCENDENT);
+
+ // Test compound name
+ path = path + "/grand-child";
+ assertSameName(path, baseName, "some-child/grand-child", NameScope.DESCENDENT);
+
+ // Test relative names
+ assertSameName(path, baseName, "./some-child/grand-child", NameScope.DESCENDENT);
+ assertSameName(path, baseName, "./nada/../some-child/grand-child", NameScope.DESCENDENT);
+ assertSameName(path, baseName, "some-child/./grand-child", NameScope.DESCENDENT);
+
+ // Test badly formed descendent names
+ checkDescendentNames(baseName, NameScope.DESCENDENT);
}
/**
@@ -286,128 +305,91 @@ public class NamingTests extends AbstractProviderTestCase {
}
/**
- * Tests descendent name resolution.
+ * Tests resolution of relative file names via the FS manager
*/
@Test
- public void testDescendentName() throws Exception {
- final FileName baseName = getReadFolder().getName();
+ public void testRelativeURI() throws Exception {
+ // Build base dir
+ getManager().setBaseFile(getReadFolder());
- // Test direct child
- String path = baseName.getPath() + "/some-child";
- assertSameName(path, baseName, "some-child", NameScope.DESCENDENT);
+ // Locate the base dir
+ FileObject file = getManager().resolveFile(".");
+ assertSame("file object", getReadFolder(), file);
- // Test compound name
- path = path + "/grand-child";
- assertSameName(path, baseName, "some-child/grand-child", NameScope.DESCENDENT);
+ // Locate a child
+ file = getManager().resolveFile("some-child");
+ assertSame("file object", getReadFolder(), file.getParent());
- // Test relative names
- assertSameName(path, baseName, "./some-child/grand-child", NameScope.DESCENDENT);
- assertSameName(path, baseName, "./nada/../some-child/grand-child", NameScope.DESCENDENT);
- assertSameName(path, baseName, "some-child/./grand-child", NameScope.DESCENDENT);
+ // Locate a descendent
+ file = getManager().resolveFile("some-folder/some-file");
+ assertSame("file object", getReadFolder(), file.getParent().getParent());
- // Test badly formed descendent names
- checkDescendentNames(baseName, NameScope.DESCENDENT);
+ // Locate parent
+ file = getManager().resolveFile("..");
+ assertSame("file object", getReadFolder().getParent(), file);
+
+ // free basefile
+ getManager().setBaseFile((FileObject) null);
}
/**
- * Tests resolution of absolute names.
+ * Tests encoding of relative URI.
*/
@Test
- public void testAbsoluteNames() throws Exception {
- // Test against the base folder
- FileName name = getReadFolder().getName();
- checkAbsoluteNames(name);
+ public void testRelativeUriEncoding() throws Exception {
+ // Build base dir
+ getManager().setBaseFile(getReadFolder());
+ final String path = getReadFolder().getName().getPath();
- // Test against the root
- name = getReadFolder().getFileSystem().getRoot().getName();
- checkAbsoluteNames(name);
+ // §1 Encode "some file"
+ FileObject file = getManager().resolveFile("%73%6f%6d%65%20%66%69%6c%65");
+ assertEquals(path + "/some file", file.getName().getPathDecoded());
- // Test against some unknown file
- name = getManager().resolveName(name, "a/b/unknown");
- checkAbsoluteNames(name);
- }
+ // §2 Encode "."
+ file = getManager().resolveFile("%2e");
+ // 18-6-2005 imario@apache.org: no need to keep the "current directory"
+ // assertEquals(path + "/.", file.getName().getPathDecoded());
+ assertEquals(path, file.getName().getPathDecoded());
- /**
- * Tests resolution of absolute names.
- */
- private void checkAbsoluteNames(final FileName name) throws Exception {
- // Root
- assertSameName("/", name, "/");
- assertSameName("/", name, "//");
- assertSameName("/", name, "/.");
- assertSameName("/", name, "/some file/..");
+ // §3 Encode '%'
+ file = getManager().resolveFile("a%25");
+ assertEquals(path + "/a%", file.getName().getPathDecoded());
- // Some absolute names
- assertSameName("/a", name, "/a");
- assertSameName("/a", name, "/./a");
- assertSameName("/a", name, "/a/.");
- assertSameName("/a/b", name, "/a/b");
+ // §4 Encode /
+ file = getManager().resolveFile("dir%2fchild");
+ assertEquals(path + "/dir/child", file.getName().getPathDecoded());
- // Some bad names
- assertBadName(name, "/..", NameScope.FILE_SYSTEM);
- assertBadName(name, "/a/../..", NameScope.FILE_SYSTEM);
- }
+ // §5 Encode \
+ file = getManager().resolveFile("dir%5cchild");
+ // 18-6-2005 imario@apache.org: all file separators normalized to "/"
+ // decided to do this to get the same behavior as in §4 on windows
+ // platforms
+ // assertEquals(path + "/dir\\child", file.getName().getPathDecoded());
+ assertEquals(path + "/dir/child", file.getName().getPathDecoded());
- /**
- * Asserts that a particular relative name is invalid for a particular scope.
- */
- private void assertBadName(final FileName name, final String relName, final NameScope scope) {
+ // §6 Use "%" literal
try {
- getManager().resolveName(name, relName, scope);
- fail("expected failure");
+ getManager().resolveFile("%");
+ fail();
} catch (final FileSystemException e) {
- // TODO - should check error message
}
- }
-
- /**
- * Tests conversion from absolute to relative names.
- */
- @Test
- public void testAbsoluteNameConvert() throws Exception {
- final FileName baseName = getReadFolder().getName();
- String path = "/test1/test2";
- FileName name = getManager().resolveName(baseName, path);
- assertEquals(path, name.getPath());
-
- // Try child and descendent names
- testRelName(name, "child");
- testRelName(name, "child1/child2");
-
- // Try own name
- testRelName(name, ".");
-
- // Try parent, and root
- testRelName(name, "..");
- testRelName(name, "../..");
-
- // Try sibling and descendent of sibling
- testRelName(name, "../sibling");
- testRelName(name, "../sibling/child");
-
- // Try siblings with similar names
- testRelName(name, "../test2_not");
- testRelName(name, "../test2_not/child");
- testRelName(name, "../test");
- testRelName(name, "../test/child");
-
- // Try unrelated
- testRelName(name, "../../unrelated");
- testRelName(name, "../../test");
- testRelName(name, "../../test/child");
-
- // Test against root
- path = "/";
- name = getManager().resolveName(baseName, path);
- assertEquals(path, name.getPath());
+ // §7 Not enough digits in encoded char
+ try {
+ getManager().resolveFile("%5");
+ fail();
+ } catch (final FileSystemException e) {
+ }
- // Try child and descendent names (against root)
- testRelName(name, "child");
- testRelName(name, "child1/child2");
+ // §8 Invalid digit in encoded char
+ try {
+ getManager().resolveFile("%q");
+ fail();
+ } catch (final FileSystemException e) {
+ }
- // Try own name (against root)
- testRelName(name, ".");
+ // free basefile
+ getManager().setBaseFile((FileObject) null);
}
/**
@@ -420,4 +402,22 @@ public class NamingTests extends AbstractProviderTestCase {
final String actualRelPath = baseName.getRelativeName(expectedName);
assertEquals(relPath, actualRelPath);
}
+
+ /**
+ * Tests the root file name.
+ */
+ @Test
+ public void testRootFileName() throws Exception {
+ // Locate the root file
+ final FileName rootName = getReadFolder().getFileSystem().getRoot().getName();
+
+ // Test that the root path is "/"
+ assertEquals("root path", "/", rootName.getPath());
+
+ // Test that the root basname is ""
+ assertEquals("root base name", "", rootName.getBaseName());
+
+ // Test that the root name has no parent
+ assertNull("root parent", rootName.getParent());
+ }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/PatternFileSelectorTest.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/PatternFileSelectorTest.java
index f7cce5d..52781a2 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/PatternFileSelectorTest.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/PatternFileSelectorTest.java
@@ -44,6 +44,10 @@ public class PatternFileSelectorTest {
private static final int FilesPerExtensionCount = 3;
+ static FileObject getBaseFolder() {
+ return BaseFolder;
+ }
+
/**
* Creates a RAM FS.
*
@@ -78,28 +82,6 @@ public class PatternFileSelectorTest {
}
/**
- * Tests a null selector.
- *
- * @throws Exception
- */
- @Test(expected = NullPointerException.class)
- public void testNullString() throws Exception {
- // Yep, this will blow up.
- new PatternFileSelector((String) null);
- }
-
- /**
- * Tests matching all
- *
- * @throws Exception
- */
- @Test
- public void testMatchAll() throws Exception {
- final FileObject[] list = BaseFolder.findFiles(new PatternFileSelector(".*"));
- assertEquals(EntryCount, list.length);
- }
-
- /**
* Tests a one extension selector.
*
* @throws Exception
@@ -132,6 +114,17 @@ public class PatternFileSelectorTest {
}
/**
+ * Tests matching all
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testMatchAll() throws Exception {
+ final FileObject[] list = BaseFolder.findFiles(new PatternFileSelector(".*"));
+ assertEquals(EntryCount, list.length);
+ }
+
+ /**
* Tests matching partial file names
*
* @throws Exception
@@ -155,8 +148,15 @@ public class PatternFileSelectorTest {
assertEquals("b.htm", list[0].getName().getBaseName());
}
- static FileObject getBaseFolder() {
- return BaseFolder;
+ /**
+ * Tests a null selector.
+ *
+ * @throws Exception
+ */
+ @Test(expected = NullPointerException.class)
+ public void testNullString() throws Exception {
+ // Yep, this will blow up.
+ new PatternFileSelector((String) null);
}
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/PermissionsTests.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/PermissionsTests.java
index d4d6aed..61555a0 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/PermissionsTests.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/PermissionsTests.java
@@ -34,6 +34,28 @@ import org.junit.Test;
public class PermissionsTests extends AbstractProviderTestCase {
public static final String FILENAME = "permission.txt";
+ private FileObject createTestFile() throws Exception {
+ // Get the scratch folder
+ final FileObject scratchFolder = getWriteFolder();
+ assertNotNull(scratchFolder);
+
+ // Make sure the test folder is empty
+ scratchFolder.delete(Selectors.EXCLUDE_SELF);
+ scratchFolder.createFolder();
+
+ // Create direct child of the test folder
+ final FileObject file = scratchFolder.resolveFile(FILENAME);
+ assertFalse(file.exists());
+
+ // Create the source file
+ final String content = "Here is some sample content for the file. Blah Blah Blah.";
+
+ try (OutputStream os = file.getContent().getOutputStream()) {
+ os.write(content.getBytes(StandardCharsets.UTF_8));
+ }
+ return file;
+ }
+
/**
* Returns the capabilities required by the tests of this test case.
*/
@@ -44,6 +66,26 @@ public class PermissionsTests extends AbstractProviderTestCase {
}
/**
+ * Returns true if the file system is a LocalFileSystem on Windows
+ */
+ private boolean isWindows() {
+ return SystemUtils.IS_OS_WINDOWS && this.getFileSystem() instanceof LocalFileSystem;
+ }
+
+ /**
+ * Clean up the permission-modified file to not affect other tests.
+ */
+ @Override
+ protected void tearDown() throws Exception {
+ final FileObject scratchFolder = getWriteFolder();
+ final FileObject file = scratchFolder.resolveFile(FILENAME);
+ file.setWritable(true, true);
+ file.delete();
+
+ super.tearDown();
+ }
+
+ /**
* Tests for the execution permission.
*/
@Test
@@ -70,26 +112,6 @@ public class PermissionsTests extends AbstractProviderTestCase {
}
/**
- * Tests for the writable permission
- */
- @Test
- public void testWriteable() throws Exception {
- final FileObject file = createTestFile();
-
- // Set the write permission for owner
- Assert.assertTrue("Setting write permission failed: " + file, file.setWritable(true, true));
- Assert.assertTrue("File expected to be writable: " + file, file.isWriteable());
-
- // Set the write permission for all
- Assert.assertTrue("Setting write permission failed: " + file, file.setWritable(true, false));
- Assert.assertTrue("File expected to be writable: " + file, file.isWriteable());
-
- // Clear the write permission
- Assert.assertTrue("Setting write permission failed: " + file, file.setWritable(false, true));
- Assert.assertFalse("File expected to be not writable: " + file, file.isWriteable());
- }
-
- /**
* Tests for the readable permission
*/
@Test
@@ -115,44 +137,22 @@ public class PermissionsTests extends AbstractProviderTestCase {
}
/**
- * Clean up the permission-modified file to not affect other tests.
+ * Tests for the writable permission
*/
- @Override
- protected void tearDown() throws Exception {
- final FileObject scratchFolder = getWriteFolder();
- final FileObject file = scratchFolder.resolveFile(FILENAME);
- file.setWritable(true, true);
- file.delete();
-
- super.tearDown();
- }
-
- private FileObject createTestFile() throws Exception {
- // Get the scratch folder
- final FileObject scratchFolder = getWriteFolder();
- assertNotNull(scratchFolder);
-
- // Make sure the test folder is empty
- scratchFolder.delete(Selectors.EXCLUDE_SELF);
- scratchFolder.createFolder();
-
- // Create direct child of the test folder
- final FileObject file = scratchFolder.resolveFile(FILENAME);
- assertFalse(file.exists());
+ @Test
+ public void testWriteable() throws Exception {
+ final FileObject file = createTestFile();
- // Create the source file
- final String content = "Here is some sample content for the file. Blah Blah Blah.";
+ // Set the write permission for owner
+ Assert.assertTrue("Setting write permission failed: " + file, file.setWritable(true, true));
+ Assert.assertTrue("File expected to be writable: " + file, file.isWriteable());
- try (OutputStream os = file.getContent().getOutputStream()) {
- os.write(content.getBytes(StandardCharsets.UTF_8));
- }
- return file;
- }
+ // Set the write permission for all
+ Assert.assertTrue("Setting write permission failed: " + file, file.setWritable(true, false));
+ Assert.assertTrue("File expected to be writable: " + file, file.isWriteable());
- /**
- * Returns true if the file system is a LocalFileSystem on Windows
- */
- private boolean isWindows() {
- return SystemUtils.IS_OS_WINDOWS && this.getFileSystem() instanceof LocalFileSystem;
+ // Clear the write permission
+ Assert.assertTrue("Setting write permission failed: " + file, file.setWritable(false, true));
+ Assert.assertFalse("File expected to be not writable: " + file, file.isWriteable());
}
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderCacheStrategyTests.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderCacheStrategyTests.java
index d7ca2e6..53a23bf 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderCacheStrategyTests.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderCacheStrategyTests.java
@@ -26,6 +26,24 @@ import org.junit.Test;
* Test the cache stragey
*/
public class ProviderCacheStrategyTests extends AbstractProviderTestCase {
+ public void assertContains(final FileObject[] fos, final String string) {
+ for (final FileObject fo : fos) {
+ if (string.equals(fo.getName().getBaseName())) {
+ return;
+ }
+ }
+
+ fail(string + " should be seen");
+ }
+
+ public void assertContainsNot(final FileObject[] fos, final String string) {
+ for (final FileObject fo : fos) {
+ if (string.equals(fo.getName().getBaseName())) {
+ fail(string + " should not be seen");
+ }
+ }
+ }
+
/**
* Returns the capabilities required by the tests of this test case.
*/
@@ -69,10 +87,10 @@ public class ProviderCacheStrategyTests extends AbstractProviderTestCase {
}
/**
- * Test the on_resolve strategy
+ * Test the on_call strategy
*/
@Test
- public void testOnResolveCache() throws Exception {
+ public void testOnCallCache() throws Exception {
final FileObject scratchFolder = getWriteFolder();
if (FileObjectUtils.isInstanceOf(getBaseFolder(), RamFileObject.class)
|| scratchFolder.getFileSystem() instanceof VirtualFileSystem) {
@@ -83,11 +101,11 @@ public class ProviderCacheStrategyTests extends AbstractProviderTestCase {
scratchFolder.delete(Selectors.EXCLUDE_SELF);
final DefaultFileSystemManager fs = createManager();
- fs.setCacheStrategy(CacheStrategy.ON_RESOLVE);
+ fs.setCacheStrategy(CacheStrategy.ON_CALL);
fs.init();
final FileObject foBase2 = getBaseTestFolder(fs);
- FileObject cachedFolder = foBase2.resolveFile(scratchFolder.getName().getPath());
+ final FileObject cachedFolder = foBase2.resolveFile(scratchFolder.getName().getPath());
FileObject[] fos = cachedFolder.getChildren();
assertContainsNot(fos, "file1.txt");
@@ -95,18 +113,14 @@ public class ProviderCacheStrategyTests extends AbstractProviderTestCase {
scratchFolder.resolveFile("file1.txt").createFile();
fos = cachedFolder.getChildren();
- assertContainsNot(fos, "file1.txt");
-
- cachedFolder = foBase2.resolveFile(scratchFolder.getName().getPath());
- fos = cachedFolder.getChildren();
assertContains(fos, "file1.txt");
}
/**
- * Test the on_call strategy
+ * Test the on_resolve strategy
*/
@Test
- public void testOnCallCache() throws Exception {
+ public void testOnResolveCache() throws Exception {
final FileObject scratchFolder = getWriteFolder();
if (FileObjectUtils.isInstanceOf(getBaseFolder(), RamFileObject.class)
|| scratchFolder.getFileSystem() instanceof VirtualFileSystem) {
@@ -117,11 +131,11 @@ public class ProviderCacheStrategyTests extends AbstractProviderTestCase {
scratchFolder.delete(Selectors.EXCLUDE_SELF);
final DefaultFileSystemManager fs = createManager();
- fs.setCacheStrategy(CacheStrategy.ON_CALL);
+ fs.setCacheStrategy(CacheStrategy.ON_RESOLVE);
fs.init();
final FileObject foBase2 = getBaseTestFolder(fs);
- final FileObject cachedFolder = foBase2.resolveFile(scratchFolder.getName().getPath());
+ FileObject cachedFolder = foBase2.resolveFile(scratchFolder.getName().getPath());
FileObject[] fos = cachedFolder.getChildren();
assertContainsNot(fos, "file1.txt");
@@ -129,24 +143,10 @@ public class ProviderCacheStrategyTests extends AbstractProviderTestCase {
scratchFolder.resolveFile("file1.txt").createFile();
fos = cachedFolder.getChildren();
- assertContains(fos, "file1.txt");
- }
-
- public void assertContainsNot(final FileObject[] fos, final String string) {
- for (final FileObject fo : fos) {
- if (string.equals(fo.getName().getBaseName())) {
- fail(string + " should not be seen");
- }
- }
- }
-
- public void assertContains(final FileObject[] fos, final String string) {
- for (final FileObject fo : fos) {
- if (string.equals(fo.getName().getBaseName())) {
- return;
- }
- }
+ assertContainsNot(fos, "file1.txt");
- fail(string + " should be seen");
+ cachedFolder = foBase2.resolveFile(scratchFolder.getName().getPath());
+ fos = cachedFolder.getChildren();
+ assertContains(fos, "file1.txt");
}
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderDeleteTests.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderDeleteTests.java
index 13876f0..f3edd5a 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderDeleteTests.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderDeleteTests.java
@@ -42,15 +42,6 @@ public class ProviderDeleteTests extends AbstractProviderTestCase {
}
/**
- * Returns the capabilities required by the tests of this test case.
- */
- @Override
- protected Capability[] getRequiredCapabilities() {
- return new Capability[] { Capability.CREATE, Capability.DELETE, Capability.GET_TYPE,
- Capability.LIST_CHILDREN, };
- }
-
- /**
* Sets up a scratch folder for the test to use.
*/
protected FileObject createScratchFolder() throws Exception {
@@ -73,13 +64,27 @@ public class ProviderDeleteTests extends AbstractProviderTestCase {
}
/**
- * deletes the complete structure
+ * Returns the capabilities required by the tests of this test case.
+ */
+ @Override
+ protected Capability[] getRequiredCapabilities() {
+ return new Capability[] { Capability.CREATE, Capability.DELETE, Capability.GET_TYPE,
+ Capability.LIST_CHILDREN, };
+ }
+
+ /**
+ * deletes files
*/
@Test
- public void testDeleteFiles() throws Exception {
+ public void testDeleteAllFiles() throws Exception {
final FileObject scratchFolder = createScratchFolder();
- assertEquals(4, scratchFolder.delete(Selectors.EXCLUDE_SELF));
+ final int deleteCount = scratchFolder.delete(new FileTypeSelector(FileType.FILE));
+ if (deleteCount < 2) {
+ // Slow deletion in an embedded server perhaps (FTPS for example).
+ Thread.sleep(500);
+ }
+ assertEquals(2, deleteCount);
}
/**
@@ -95,30 +100,25 @@ public class ProviderDeleteTests extends AbstractProviderTestCase {
}
/**
- * Deletes a non existent file
+ * deletes the complete structure
*/
@Test
- public void testDeleteNonExistantFile() throws Exception {
+ public void testDeleteFiles() throws Exception {
final FileObject scratchFolder = createScratchFolder();
- final FileObject file = scratchFolder.resolveFile("dir1/aa.txt");
-
- assertFalse(file.delete());
+ assertEquals(4, scratchFolder.delete(Selectors.EXCLUDE_SELF));
}
/**
- * deletes files
+ * Deletes a non existent file
*/
@Test
- public void testDeleteAllFiles() throws Exception {
+ public void testDeleteNonExistantFile() throws Exception {
final FileObject scratchFolder = createScratchFolder();
- final int deleteCount = scratchFolder.delete(new FileTypeSelector(FileType.FILE));
- if (deleteCount < 2) {
- // Slow deletion in an embedded server perhaps (FTPS for example).
- Thread.sleep(500);
- }
- assertEquals(2, deleteCount);
+ final FileObject file = scratchFolder.resolveFile("dir1/aa.txt");
+
+ assertFalse(file.delete());
}
/**
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderRandomReadWriteTests.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderRandomReadWriteTests.java
index 65df227..afdb826 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderRandomReadWriteTests.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderRandomReadWriteTests.java
@@ -27,15 +27,6 @@ public class ProviderRandomReadWriteTests extends AbstractProviderTestCase {
private static final String TEST_DATA = "This is a test file.";
/**
- * Returns the capabilities required by the tests of this test case.
- */
- @Override
- protected Capability[] getRequiredCapabilities() {
- return new Capability[] { Capability.GET_TYPE, Capability.CREATE, Capability.RANDOM_ACCESS_READ,
- Capability.RANDOM_ACCESS_WRITE };
- }
-
- /**
* Sets up a scratch folder for the test to use.
*/
protected FileObject createScratchFolder() throws Exception {
@@ -49,6 +40,15 @@ public class ProviderRandomReadWriteTests extends AbstractProviderTestCase {
}
/**
+ * Returns the capabilities required by the tests of this test case.
+ */
+ @Override
+ protected Capability[] getRequiredCapabilities() {
+ return new Capability[] { Capability.GET_TYPE, Capability.CREATE, Capability.RANDOM_ACCESS_READ,
+ Capability.RANDOM_ACCESS_WRITE };
+ }
+
+ /**
* Writes a file
*/
@Test
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderReadTests.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderReadTests.java
index 1ec8399..f7d69ad 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderReadTests.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderReadTests.java
@@ -33,33 +33,6 @@ import org.junit.Test;
public class ProviderReadTests extends AbstractProviderTestCase {
/**
- * Returns the read folder named "dir1".
- *
- * @return the read folder named "dir1".
- * @throws FileSystemException
- */
- protected FileObject getReadFolderDir1() throws FileSystemException {
- return getReadFolder().resolveFile("dir1");
- }
-
- /**
- * Returns the capabilities required by the tests of this test case.
- */
- @Override
- protected Capability[] getRequiredCapabilities() {
- return new Capability[] { Capability.GET_TYPE, Capability.LIST_CHILDREN, Capability.READ_CONTENT };
- }
-
- /**
- * Walks the base folder structure, asserting it contains exactly the expected files and folders.
- */
- @Test
- public void testStructure() throws Exception {
- final FileInfo baseInfo = buildExpectedStructure();
- assertSameStructure(getReadFolder(), baseInfo);
- }
-
- /**
* Walks a folder structure, asserting it contains exactly the expected files and folders.
*/
protected void assertSameStructure(final FileObject folder, final FileInfo expected) throws Exception {
@@ -118,59 +91,87 @@ public class ProviderReadTests extends AbstractProviderTestCase {
}
/**
- * Tests type determination.
+ * Returns the read folder named "dir1".
+ *
+ * @return the read folder named "dir1".
+ * @throws FileSystemException
+ */
+ protected FileObject getReadFolderDir1() throws FileSystemException {
+ return getReadFolder().resolveFile("dir1");
+ }
+
+ /**
+ * Returns the capabilities required by the tests of this test case.
+ */
+ @Override
+ protected Capability[] getRequiredCapabilities() {
+ return new Capability[] { Capability.GET_TYPE, Capability.LIST_CHILDREN, Capability.READ_CONTENT };
+ }
+
+ private FileObject resolveFile1Txt() throws FileSystemException {
+ return getReadFolder().resolveFile("file1.txt");
+ }
+
+ /**
+ * Tests can perform operations on a folder while reading from a different files.
*/
@Test
- public void testType() throws Exception {
- // Test a file
- FileObject file = resolveFile1Txt();
- assertSame(FileType.FILE, file.getType());
- assertTrue(file.isFile());
+ public void testConcurrentReadFolder() throws Exception {
+ final FileObject file = resolveFile1Txt();
+ assertTrue(file.exists());
+ final FileObject folder = getReadFolderDir1();
+ assertTrue(folder.exists());
- // Test a folder
- file = getReadFolderDir1();
- assertSame(FileType.FOLDER, file.getType());
- assertTrue(file.isFolder());
+ // Start reading from the file
+ try (InputStream instr = file.getContent().getInputStream()) {
+ // Do some operations
+ folder.exists();
+ folder.getType();
+ folder.getChildren();
+ }
+ }
- // Test an unknown file
- file = getReadFolder().resolveFile("unknown-child");
- assertSame(FileType.IMAGINARY, file.getType());
+ /**
+ * Tests that we can traverse a folder that has JAR name.
+ */
+ @Test
+ public void testDotJarFolderName() throws Exception {
+ final FileObject folder = getReadFolderDir1().resolveFile("subdir4.jar");
+ Assert.assertTrue(folder.exists());
+ final FileObject file = folder.resolveFile("file1.txt");
+ Assert.assertTrue(file.exists());
}
/**
- * Tests the contents of root of file system can be listed.
+ * Tests that a folder can't be layered.
*/
@Test
- public void testRoot() throws FileSystemException {
- if (!this.getProviderConfig().isFileSystemRootAccessible()) {
- return;
+ public void testDotJarFolderNameLayer() throws Exception {
+ final FileObject folder = getReadFolderDir1().resolveFile("subdir4.jar");
+ Assert.assertTrue("subdir4.jar/ must exist as folder, check test setup.", folder.isFolder());
+ Assert.assertFalse("subdir4.jar/ must not be layerable", getManager().canCreateFileSystem(folder));
+ try {
+ final FileObject ignored = getManager().createFileSystem(folder);
+ fail("Should not be able to create a layered filesystem on a directory. " + ignored);
+ } catch (final FileSystemException e) {
+ assertSame("Creation of layered filesystem should fail" + e, "vfs.impl/no-provider-for-file.error",
+ e.getCode());
}
- final FileSystem fs = getFileSystem();
- final String uri = fs.getRootURI();
- final FileObject file = getManager().resolveFile(uri, fs.getFileSystemOptions());
- file.getChildren();
}
/**
- * Tests that FileObjects can be sorted.
+ * Tests that findFiles() works.
*/
@Test
- public void testSort() throws FileSystemException {
+ public void testFindFiles() throws Exception {
final FileInfo fileInfo = buildExpectedStructure();
final VerifyingFileSelector selector = new VerifyingFileSelector(fileInfo);
// Find the files
final FileObject[] actualFiles = getReadFolder().findFiles(selector);
- Arrays.sort(actualFiles);
- FileObject prevActualFile = actualFiles[0];
- for (final FileObject actualFile : actualFiles) {
- assertTrue(prevActualFile.toString().compareTo(actualFile.toString()) <= 0);
- prevActualFile = actualFile;
- }
// Compare actual and expected list of files
final List<FileObject> expectedFiles = selector.finish();
- Collections.sort(expectedFiles);
assertEquals(expectedFiles.size(), actualFiles.length);
final int count = expectedFiles.size();
for (int i = 0; i < count; i++) {
@@ -210,21 +211,21 @@ public class ProviderReadTests extends AbstractProviderTestCase {
}
/**
- * Tests that test read folder is not a symbolic link.
+ * Tests that test read folder is readable.
*/
@Test
- public void testFolderIsSymbolicLink() throws Exception {
+ public void testFolderIsReadable() throws Exception {
final FileObject folder = getReadFolderDir1();
- Assert.assertFalse(folder.isSymbolicLink());
+ Assert.assertTrue(folder.isReadable());
}
/**
- * Tests that test read folder is readable.
+ * Tests that test read folder is not a symbolic link.
*/
@Test
- public void testFolderIsReadable() throws Exception {
+ public void testFolderIsSymbolicLink() throws Exception {
final FileObject folder = getReadFolderDir1();
- Assert.assertTrue(folder.isReadable());
+ Assert.assertFalse(folder.isSymbolicLink());
}
@Test
@@ -245,10 +246,6 @@ public class ProviderReadTests extends AbstractProviderTestCase {
assertNotNull(contentInfo);
}
- private FileObject resolveFile1Txt() throws FileSystemException {
- return getReadFolder().resolveFile("file1.txt");
- }
-
/**
* Tests can read multiple time end of stream of empty file
*/
@@ -288,37 +285,39 @@ public class ProviderReadTests extends AbstractProviderTestCase {
}
/**
- * Tests can perform operations on a folder while reading from a different files.
+ * Tests the contents of root of file system can be listed.
*/
@Test
- public void testConcurrentReadFolder() throws Exception {
- final FileObject file = resolveFile1Txt();
- assertTrue(file.exists());
- final FileObject folder = getReadFolderDir1();
- assertTrue(folder.exists());
-
- // Start reading from the file
- try (InputStream instr = file.getContent().getInputStream()) {
- // Do some operations
- folder.exists();
- folder.getType();
- folder.getChildren();
+ public void testRoot() throws FileSystemException {
+ if (!this.getProviderConfig().isFileSystemRootAccessible()) {
+ return;
}
+ final FileSystem fs = getFileSystem();
+ final String uri = fs.getRootURI();
+ final FileObject file = getManager().resolveFile(uri, fs.getFileSystemOptions());
+ file.getChildren();
}
/**
- * Tests that findFiles() works.
+ * Tests that FileObjects can be sorted.
*/
@Test
- public void testFindFiles() throws Exception {
+ public void testSort() throws FileSystemException {
final FileInfo fileInfo = buildExpectedStructure();
final VerifyingFileSelector selector = new VerifyingFileSelector(fileInfo);
// Find the files
final FileObject[] actualFiles = getReadFolder().findFiles(selector);
+ Arrays.sort(actualFiles);
+ FileObject prevActualFile = actualFiles[0];
+ for (final FileObject actualFile : actualFiles) {
+ assertTrue(prevActualFile.toString().compareTo(actualFile.toString()) <= 0);
+ prevActualFile = actualFile;
+ }
// Compare actual and expected list of files
final List<FileObject> expectedFiles = selector.finish();
+ Collections.sort(expectedFiles);
assertEquals(expectedFiles.size(), actualFiles.length);
final int count = expectedFiles.size();
for (int i = 0; i < count; i++) {
@@ -329,30 +328,31 @@ public class ProviderReadTests extends AbstractProviderTestCase {
}
/**
- * Tests that we can traverse a folder that has JAR name.
+ * Walks the base folder structure, asserting it contains exactly the expected files and folders.
*/
@Test
- public void testDotJarFolderName() throws Exception {
- final FileObject folder = getReadFolderDir1().resolveFile("subdir4.jar");
- Assert.assertTrue(folder.exists());
- final FileObject file = folder.resolveFile("file1.txt");
- Assert.assertTrue(file.exists());
+ public void testStructure() throws Exception {
+ final FileInfo baseInfo = buildExpectedStructure();
+ assertSameStructure(getReadFolder(), baseInfo);
}
/**
- * Tests that a folder can't be layered.
+ * Tests type determination.
*/
@Test
- public void testDotJarFolderNameLayer() throws Exception {
- final FileObject folder = getReadFolderDir1().resolveFile("subdir4.jar");
- Assert.assertTrue("subdir4.jar/ must exist as folder, check test setup.", folder.isFolder());
- Assert.assertFalse("subdir4.jar/ must not be layerable", getManager().canCreateFileSystem(folder));
- try {
- final FileObject ignored = getManager().createFileSystem(folder);
- fail("Should not be able to create a layered filesystem on a directory. " + ignored);
- } catch (final FileSystemException e) {
- assertSame("Creation of layered filesystem should fail" + e, "vfs.impl/no-provider-for-file.error",
- e.getCode());
- }
+ public void testType() throws Exception {
+ // Test a file
+ FileObject file = resolveFile1Txt();
+ assertSame(FileType.FILE, file.getType());
+ assertTrue(file.isFile());
+
+ // Test a folder
+ file = getReadFolderDir1();
+ assertSame(FileType.FOLDER, file.getType());
+ assertTrue(file.isFolder());
+
+ // Test an unknown file
+ file = getReadFolder().resolveFile("unknown-child");
+ assertSame(FileType.IMAGINARY, file.getType());
}
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderRenameTests.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderRenameTests.java
index 056faeb..5ee9564 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderRenameTests.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderRenameTests.java
@@ -28,15 +28,6 @@ import org.junit.Test;
*/
public class ProviderRenameTests extends AbstractProviderTestCase {
/**
- * Returns the capabilities required by the tests of this test case.
- */
- @Override
- protected Capability[] getRequiredCapabilities() {
- return new Capability[] { Capability.CREATE, Capability.DELETE, Capability.GET_TYPE, Capability.LIST_CHILDREN,
- Capability.READ_CONTENT, Capability.WRITE_CONTENT, Capability.RENAME };
- }
-
- /**
* Sets up a scratch folder for the test to use.
*/
protected FileObject createScratchFolder() throws Exception {
@@ -49,6 +40,27 @@ public class ProviderRenameTests extends AbstractProviderTestCase {
return scratchFolder;
}
+ private String createTestFile(final FileObject file)
+ throws FileSystemException, IOException, UnsupportedEncodingException, Exception {
+ // Create the source file
+ final String content = "Here is some sample content for the file. Blah Blah Blah.";
+
+ try (OutputStream os = file.getContent().getOutputStream()) {
+ os.write(content.getBytes(StandardCharsets.UTF_8));
+ }
+ assertSameContent(content, file);
+ return content;
+ }
+
+ /**
+ * Returns the capabilities required by the tests of this test case.
+ */
+ @Override
+ protected Capability[] getRequiredCapabilities() {
+ return new Capability[] { Capability.CREATE, Capability.DELETE, Capability.GET_TYPE, Capability.LIST_CHILDREN,
+ Capability.READ_CONTENT, Capability.WRITE_CONTENT, Capability.RENAME };
+ }
+
private void moveFile(final FileObject scratchFolder, final FileObject file, final String content)
throws FileSystemException, Exception {
final FileObject fileMove = scratchFolder.resolveFile("file1move.txt");
@@ -66,18 +78,6 @@ public class ProviderRenameTests extends AbstractProviderTestCase {
assertTrue(fileMove.delete());
}
- private String createTestFile(final FileObject file)
- throws FileSystemException, IOException, UnsupportedEncodingException, Exception {
- // Create the source file
- final String content = "Here is some sample content for the file. Blah Blah Blah.";
-
- try (OutputStream os = file.getContent().getOutputStream()) {
- os.write(content.getBytes(StandardCharsets.UTF_8));
- }
- assertSameContent(content, file);
- return content;
- }
-
/**
* Tests create-delete-create-a-file sequence on the same file system.
*/
@@ -96,6 +96,27 @@ public class ProviderRenameTests extends AbstractProviderTestCase {
}
/**
+ * Moves a file from a child folder to a parent folder to test what happens when the original folder is now empty.
+ *
+ * See [VFS-298] FTP: Exception is thrown when renaming a file.
+ */
+ @Test
+ public void testRenameFileAndLeaveFolderEmpty() throws Exception {
+ final FileObject scratchFolder = createScratchFolder();
+ final FileObject folder = scratchFolder.resolveFile("folder");
+ folder.createFolder();
+ assertTrue(folder.exists());
+ final FileObject file = folder.resolveFile("file1.txt");
+ assertFalse(file.exists());
+
+ final String content = createTestFile(file);
+
+ // Make sure we can move the new file to another file on the same file system
+ moveFile(scratchFolder, file, content);
+ assertEquals(0, folder.getChildren().length);
+ }
+
+ /**
* Tests moving a file to empty folder.
* <P>
* This fails with VFS-558, but only with a CacheStrategy.ON_CALL.
@@ -117,25 +138,4 @@ public class ProviderRenameTests extends AbstractProviderTestCase {
moveFile(destFolder, file, content);
}
-
- /**
- * Moves a file from a child folder to a parent folder to test what happens when the original folder is now empty.
- *
- * See [VFS-298] FTP: Exception is thrown when renaming a file.
- */
- @Test
- public void testRenameFileAndLeaveFolderEmpty() throws Exception {
- final FileObject scratchFolder = createScratchFolder();
- final FileObject folder = scratchFolder.resolveFile("folder");
- folder.createFolder();
- assertTrue(folder.exists());
- final FileObject file = folder.resolveFile("file1.txt");
- assertFalse(file.exists());
-
- final String content = createTestFile(file);
-
- // Make sure we can move the new file to another file on the same file system
- moveFile(scratchFolder, file, content);
- assertEquals(0, folder.getChildren().length);
- }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderTestConfig.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderTestConfig.java
index 591e8cb..03a944a 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderTestConfig.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderTestConfig.java
@@ -24,16 +24,6 @@ import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
*/
public interface ProviderTestConfig {
/**
- * Returns a DefaultFileSystemManager instance (or subclass instance).
- */
- DefaultFileSystemManager getDefaultFileSystemManager();
-
- /**
- * Prepares the file system manager.
- */
- void prepare(DefaultFileSystemManager manager) throws Exception;
-
- /**
* Returns the base folder for tests. This folder must exist, and contain the following structure:
* <ul>
* <li>"/read-tests"</li>
@@ -43,6 +33,11 @@ public interface ProviderTestConfig {
FileObject getBaseTestFolder(FileSystemManager manager) throws Exception;
/**
+ * Returns a DefaultFileSystemManager instance (or subclass instance).
+ */
+ DefaultFileSystemManager getDefaultFileSystemManager();
+
+ /**
* Returns the filesCache implementation used for tests.
*/
FilesCache getFilesCache();
@@ -55,4 +50,9 @@ public interface ProviderTestConfig {
* @return Whether or not the root of test file system is accessible.
*/
boolean isFileSystemRootAccessible();
+
+ /**
+ * Prepares the file system manager.
+ */
+ void prepare(DefaultFileSystemManager manager) throws Exception;
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderWriteAppendTests.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderWriteAppendTests.java
index ba2d9f5..5519c9d 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderWriteAppendTests.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderWriteAppendTests.java
@@ -26,15 +26,6 @@ import org.junit.Test;
*/
public class ProviderWriteAppendTests extends AbstractProviderTestCase {
/**
- * Returns the capabilities required by the tests of this test case.
- */
- @Override
- protected Capability[] getRequiredCapabilities() {
- return new Capability[] { Capability.CREATE, Capability.DELETE, Capability.GET_TYPE, Capability.LIST_CHILDREN,
- Capability.READ_CONTENT, Capability.WRITE_CONTENT, Capability.APPEND_CONTENT };
- }
-
- /**
* Sets up a scratch folder for the test to use.
*/
protected FileObject createScratchFolder() throws Exception {
@@ -48,6 +39,15 @@ public class ProviderWriteAppendTests extends AbstractProviderTestCase {
}
/**
+ * Returns the capabilities required by the tests of this test case.
+ */
+ @Override
+ protected Capability[] getRequiredCapabilities() {
+ return new Capability[] { Capability.CREATE, Capability.DELETE, Capability.GET_TYPE, Capability.LIST_CHILDREN,
+ Capability.READ_CONTENT, Capability.WRITE_CONTENT, Capability.APPEND_CONTENT };
+ }
+
+ /**
* Tests create-delete-create-a-file sequence on the same file system.
*/
@Test
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderWriteTests.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderWriteTests.java
index 85a772f..6cfff24 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderWriteTests.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/ProviderWriteTests.java
@@ -31,17 +31,86 @@ import org.junit.Test;
*/
public class ProviderWriteTests extends AbstractProviderTestCase {
- protected FileObject getReadFolderDir1() throws FileSystemException {
- return getReadFolder().resolveFile("dir1");
+ /**
+ * A test listener.
+ */
+ private static class TestListener implements FileListener {
+ private static final Object CREATE = "create";
+ private static final Object DELETE = "delete";
+ private static final Object CHANGED = "changed";
+ private final FileObject file;
+ private final ArrayList<Object> events = new ArrayList<>();
+
+ public TestListener(final FileObject file) {
+ this.file = file;
+ }
+
+ public void addCreateEvent() {
+ events.add(CREATE);
+ }
+
+ public void addDeleteEvent() {
+ events.add(DELETE);
+ }
+
+ public void assertFinished() {
+ assertEquals("Missing event", 0, events.size());
+ }
+
+ @Override
+ public void fileChanged(final FileChangeEvent event) throws Exception {
+ assertFalse("Unexpected changed event", events.isEmpty());
+ assertSame("Expecting a changed event", CHANGED, events.remove(0));
+ assertEquals(Objects.toString(file), file, event.getFileObject());
+ try {
+ assertFalse(Objects.toString(file), file.exists());
+ } catch (final FileSystemException e) {
+ fail();
+ }
+ }
+
+ /**
+ * Called when a file is created.
+ */
+ @Override
+ public void fileCreated(final FileChangeEvent event) {
+ assertFalse("Unexpected create event", events.isEmpty());
+ assertSame("Expecting a create event", CREATE, events.remove(0));
+ assertEquals(Objects.toString(file), file, event.getFileObject());
+ try {
+ assertTrue(Objects.toString(file), file.exists());
+ } catch (final FileSystemException e) {
+ fail();
+ }
+ }
+
+ /**
+ * Called when a file is deleted.
+ */
+ @Override
+ public void fileDeleted(final FileChangeEvent event) {
+ assertFalse("Unexpected delete event", events.isEmpty());
+ assertSame("Expecting a delete event", DELETE, events.remove(0));
+ assertEquals(Objects.toString(file), file, event.getFileObject());
+ try {
+ assertFalse(Objects.toString(file), file.exists());
+ } catch (final FileSystemException e) {
+ fail();
+ }
+ }
}
/**
- * Returns the capabilities required by the tests of this test case.
+ * Ensures the names of a set of files match an expected set.
*/
- @Override
- protected Capability[] getRequiredCapabilities() {
- return new Capability[] { Capability.CREATE, Capability.DELETE, Capability.GET_TYPE, Capability.LIST_CHILDREN,
- Capability.READ_CONTENT, Capability.WRITE_CONTENT };
+ private void assertSameFileSet(final Set<String> names, final FileObject[] files) {
+ // Make sure the sets are the same length
+ assertEquals(names.size(), files.length);
+
+ // Check for unexpected names
+ for (final FileObject file : files) {
+ assertTrue(names.contains(file.getName().getBaseName()));
+ }
}
/**
@@ -57,137 +126,153 @@ public class ProviderWriteTests extends AbstractProviderTestCase {
return scratchFolder;
}
+ protected FileObject getReadFolderDir1() throws FileSystemException {
+ return getReadFolder().resolveFile("dir1");
+ }
+
/**
- * Tests folder creation.
+ * Returns the capabilities required by the tests of this test case.
+ */
+ @Override
+ protected Capability[] getRequiredCapabilities() {
+ return new Capability[] { Capability.CREATE, Capability.DELETE, Capability.GET_TYPE, Capability.LIST_CHILDREN,
+ Capability.READ_CONTENT, Capability.WRITE_CONTENT };
+ }
+
+ /**
+ * Tests overwriting a file on the same file system.
*/
@Test
- public void testFolderCreate() throws Exception {
+ public void testCopyFromOverwriteSameFileSystem() throws Exception {
final FileObject scratchFolder = createScratchFolder();
// Create direct child of the test folder
- FileObject folder = scratchFolder.resolveFile("dir1");
- assertFalse(folder.exists());
- folder.createFolder();
- assertTrue(folder.exists());
- assertSame(FileType.FOLDER, folder.getType());
- assertTrue(folder.isFolder());
- assertEquals(0, folder.getChildren().length);
+ final FileObject file = scratchFolder.resolveFile("file1.txt");
+ assertFalse(file.exists());
- // Create a descendant, where the intermediate folders don't exist
- folder = scratchFolder.resolveFile("dir2/dir1/dir1");
- assertFalse(folder.exists());
- assertFalse(folder.getParent().exists());
- assertFalse(folder.getParent().getParent().exists());
- folder.createFolder();
- assertTrue(folder.exists());
- assertSame(FileType.FOLDER, folder.getType());
- assertTrue(folder.isFolder());
- assertEquals(0, folder.getChildren().length);
- assertTrue(folder.getParent().exists());
- assertTrue(folder.getParent().getParent().exists());
+ // Create the source file
+ final String content = "Here is some sample content for the file. Blah Blah Blah.";
+ try (OutputStream os = file.getContent().getOutputStream()) {
+ os.write(content.getBytes(StandardCharsets.UTF_8));
+ }
- // Test creating a folder that already exists
- assertTrue(folder.exists());
- folder.createFolder();
+ assertSameContent(content, file);
+
+ // Make sure we can copy the new file to another file on the same filesystem
+ final FileObject fileCopy = scratchFolder.resolveFile("file1copy.txt");
+ assertFalse(fileCopy.exists());
+ fileCopy.copyFrom(file, Selectors.SELECT_SELF);
+
+ assertSameContent(content, fileCopy);
+
+ // Make sure we can copy the same new file to the same target file on the same filesystem
+ assertTrue(fileCopy.exists());
+ fileCopy.copyFrom(file, Selectors.SELECT_SELF);
+
+ assertSameContent(content, fileCopy);
}
/**
- * Tests file creation
+ * Tests file copy to and from the same file system type. This was a problem w/ FTP.
*/
@Test
- public void testFileCreate() throws Exception {
+ public void testCopySameFileSystem() throws Exception {
final FileObject scratchFolder = createScratchFolder();
// Create direct child of the test folder
- FileObject file = scratchFolder.resolveFile("file1.txt");
+ final FileObject file = scratchFolder.resolveFile("file1.txt");
assertFalse(file.exists());
- file.createFile();
- assertTrue(file.exists());
- assertSame(FileType.FILE, file.getType());
- assertTrue(file.isFile());
- assertEquals(0, file.getContent().getSize());
- assertTrue(file.getContent().isEmpty());
- assertFalse(file.isHidden());
- assertFalse(file.isSymbolicLink());
- assertTrue(file.isReadable());
- assertTrue(file.isWriteable());
- // Create direct child of the test folder - special name
- file = scratchFolder.resolveFile("file1%25.txt");
- assertFalse(file.exists());
- file.createFile();
- assertTrue(file.exists());
- assertSame(FileType.FILE, file.getType());
- assertTrue(file.isFile());
- assertEquals(0, file.getContent().getSize());
- assertFalse(file.isHidden());
- assertTrue(file.isReadable());
- assertTrue(file.isWriteable());
+ // Create the source file
+ final String content = "Here is some sample content for the file. Blah Blah Blah.";
+ try (OutputStream os = file.getContent().getOutputStream()) {
+ os.write(content.getBytes(StandardCharsets.UTF_8));
+ }
- // Create a descendant, where the intermediate folders don't exist
- file = scratchFolder.resolveFile("dir1/dir1/file1.txt");
- assertFalse(file.exists());
- assertFalse(file.getParent().exists());
- assertFalse(file.getParent().getParent().exists());
- file.createFile();
- assertTrue(file.exists());
- assertSame(FileType.FILE, file.getType());
- assertTrue(file.isFile());
- assertEquals(0, file.getContent().getSize());
- assertTrue(file.getParent().exists());
- assertTrue(file.getParent().getParent().exists());
- assertFalse(file.getParent().isHidden());
- assertFalse(file.getParent().getParent().isHidden());
+ assertSameContent(content, file);
- // Test creating a file that already exists
- assertTrue(file.exists());
- file.createFile();
- assertTrue(file.exists());
- assertTrue(file.isReadable());
- assertTrue(file.isWriteable());
+ // Make sure we can copy the new file to another file on the same filesystem
+ final FileObject fileCopy = scratchFolder.resolveFile("file1copy.txt");
+ assertFalse(fileCopy.exists());
+ fileCopy.copyFrom(file, Selectors.SELECT_SELF);
+
+ assertSameContent(content, fileCopy);
}
/**
- * Tests file/folder creation with mismatched types.
+ * Tests create-delete-create-a-file sequence on the same file system.
*/
@Test
- public void testFileCreateMismatched() throws Exception {
+ public void testCreateDeleteCreateSameFileSystem() throws Exception {
final FileObject scratchFolder = createScratchFolder();
- // Create a test file and folder
- final FileObject file = scratchFolder.resolveFile("dir1/file1.txt");
- file.createFile();
- assertEquals(FileType.FILE, file.getType());
- assertTrue(file.isFile());
-
- final FileObject folder = scratchFolder.resolveFile("dir1/dir2");
- folder.createFolder();
- assertEquals(FileType.FOLDER, folder.getType());
- assertTrue(folder.isFolder());
+ // Create direct child of the test folder
+ final FileObject file = scratchFolder.resolveFile("file1.txt");
+ assertFalse(file.exists());
- // Attempt to create a file that already exists as a folder
- try {
- folder.createFile();
- fail();
- } catch (final FileSystemException exc) {
+ // Create the source file
+ final String content = "Here is some sample content for the file. Blah Blah Blah.";
+ try (OutputStream os = file.getContent().getOutputStream()) {
+ os.write(content.getBytes(StandardCharsets.UTF_8));
}
- // Attempt to create a folder that already exists as a file
- try {
- file.createFolder();
- fail();
- } catch (final FileSystemException exc) {
- }
+ assertSameContent(content, file);
- // Attempt to create a folder as a child of a file
- final FileObject folder2 = file.resolveFile("some-child");
- try {
- folder2.createFolder();
- fail();
- } catch (final FileSystemException exc) {
- }
+ // Make sure we can copy the new file to another file on the same filesystem
+ final FileObject fileCopy = scratchFolder.resolveFile("file1copy.txt");
+ assertFalse(fileCopy.exists());
+ fileCopy.copyFrom(file, Selectors.SELECT_SELF);
+
+ assertSameContent(content, fileCopy);
+
+ // Delete the file.
+ assertTrue(fileCopy.exists());
+ assertTrue(fileCopy.delete());
+
+ // Make sure we can copy the same new file to the same target file on the same filesystem
+ assertFalse(fileCopy.exists());
+ fileCopy.copyFrom(file, Selectors.SELECT_SELF);
+
+ assertSameContent(content, fileCopy);
}
+ /*
+ Tests concurrent read and write on the same file fails.
+ */
+ /*
+ * imario@apache.org leave this to some sort of LockManager public void testConcurrentReadWrite() throws Exception {
+ * final FileObject scratchFolder = createScratchFolder();
+ *
+ * final FileObject file = scratchFolder.resolveFile("file1.txt"); file.createFile();
+ *
+ * // Start reading from the file final InputStream instr = file.getContent().getInputStream();
+ *
+ * try { // Try to write to the file file.getContent().getOutputStream(); fail(); } catch (final FileSystemException
+ * e) { // Check error message assertSameMessage("vfs.provider/write-in-use.error", file, e); } finally {
+ * instr.close(); } }
+ */
+
+ /*
+ Tests concurrent writes on the same file fails.
+ */
+ /*
+ * imario@apache.org leave this to some sort of LockManager public void testConcurrentWrite() throws Exception {
+ * final FileObject scratchFolder = createScratchFolder();
+ *
+ * final FileObject file = scratchFolder.resolveFile("file1.txt"); file.createFile();
+ *
+ * // Start writing to the file final OutputStream outstr = file.getContent().getOutputStream(); final String
+ * testContent = "some content"; try { // Write some content to the first stream
+ * outstr.write(testContent.getBytes());
+ *
+ * // Try to open another output stream file.getContent().getOutputStream(); fail(); } catch (final
+ * FileSystemException e) { // Check error message assertSameMessage("vfs.provider/write-in-use.error", file, e); }
+ * finally { outstr.close(); }
+ *
+ * // Make sure that the content written to the first stream is actually applied assertSameContent(testContent,
+ * file); }
+ */
+
/**
* Tests deletion
*/
@@ -282,138 +367,135 @@ public class ProviderWriteTests extends AbstractProviderTestCase {
assertFalse(file.exists());
}
- /*
- Tests concurrent read and write on the same file fails.
- */
- /*
- * imario@apache.org leave this to some sort of LockManager public void testConcurrentReadWrite() throws Exception {
- * final FileObject scratchFolder = createScratchFolder();
- *
- * final FileObject file = scratchFolder.resolveFile("file1.txt"); file.createFile();
- *
- * // Start reading from the file final InputStream instr = file.getContent().getInputStream();
- *
- * try { // Try to write to the file file.getContent().getOutputStream(); fail(); } catch (final FileSystemException
- * e) { // Check error message assertSameMessage("vfs.provider/write-in-use.error", file, e); } finally {
- * instr.close(); } }
- */
-
- /*
- Tests concurrent writes on the same file fails.
- */
- /*
- * imario@apache.org leave this to some sort of LockManager public void testConcurrentWrite() throws Exception {
- * final FileObject scratchFolder = createScratchFolder();
- *
- * final FileObject file = scratchFolder.resolveFile("file1.txt"); file.createFile();
- *
- * // Start writing to the file final OutputStream outstr = file.getContent().getOutputStream(); final String
- * testContent = "some content"; try { // Write some content to the first stream
- * outstr.write(testContent.getBytes());
- *
- * // Try to open another output stream file.getContent().getOutputStream(); fail(); } catch (final
- * FileSystemException e) { // Check error message assertSameMessage("vfs.provider/write-in-use.error", file, e); }
- * finally { outstr.close(); }
- *
- * // Make sure that the content written to the first stream is actually applied assertSameContent(testContent,
- * file); }
- */
-
/**
- * Tests file copy to and from the same file system type. This was a problem w/ FTP.
+ * Tests file creation
*/
@Test
- public void testCopySameFileSystem() throws Exception {
+ public void testFileCreate() throws Exception {
final FileObject scratchFolder = createScratchFolder();
// Create direct child of the test folder
- final FileObject file = scratchFolder.resolveFile("file1.txt");
+ FileObject file = scratchFolder.resolveFile("file1.txt");
assertFalse(file.exists());
+ file.createFile();
+ assertTrue(file.exists());
+ assertSame(FileType.FILE, file.getType());
+ assertTrue(file.isFile());
+ assertEquals(0, file.getContent().getSize());
+ assertTrue(file.getContent().isEmpty());
+ assertFalse(file.isHidden());
+ assertFalse(file.isSymbolicLink());
+ assertTrue(file.isReadable());
+ assertTrue(file.isWriteable());
- // Create the source file
- final String content = "Here is some sample content for the file. Blah Blah Blah.";
- try (OutputStream os = file.getContent().getOutputStream()) {
- os.write(content.getBytes(StandardCharsets.UTF_8));
- }
-
- assertSameContent(content, file);
-
- // Make sure we can copy the new file to another file on the same filesystem
- final FileObject fileCopy = scratchFolder.resolveFile("file1copy.txt");
- assertFalse(fileCopy.exists());
- fileCopy.copyFrom(file, Selectors.SELECT_SELF);
-
- assertSameContent(content, fileCopy);
- }
-
- /**
- * Tests overwriting a file on the same file system.
- */
- @Test
- public void testCopyFromOverwriteSameFileSystem() throws Exception {
- final FileObject scratchFolder = createScratchFolder();
-
- // Create direct child of the test folder
- final FileObject file = scratchFolder.resolveFile("file1.txt");
+ // Create direct child of the test folder - special name
+ file = scratchFolder.resolveFile("file1%25.txt");
assertFalse(file.exists());
+ file.createFile();
+ assertTrue(file.exists());
+ assertSame(FileType.FILE, file.getType());
+ assertTrue(file.isFile());
+ assertEquals(0, file.getContent().getSize());
+ assertFalse(file.isHidden());
+ assertTrue(file.isReadable());
+ assertTrue(file.isWriteable());
- // Create the source file
- final String content = "Here is some sample content for the file. Blah Blah Blah.";
- try (OutputStream os = file.getContent().getOutputStream()) {
- os.write(content.getBytes(StandardCharsets.UTF_8));
- }
-
- assertSameContent(content, file);
-
- // Make sure we can copy the new file to another file on the same filesystem
- final FileObject fileCopy = scratchFolder.resolveFile("file1copy.txt");
- assertFalse(fileCopy.exists());
- fileCopy.copyFrom(file, Selectors.SELECT_SELF);
-
- assertSameContent(content, fileCopy);
-
- // Make sure we can copy the same new file to the same target file on the same filesystem
- assertTrue(fileCopy.exists());
- fileCopy.copyFrom(file, Selectors.SELECT_SELF);
+ // Create a descendant, where the intermediate folders don't exist
+ file = scratchFolder.resolveFile("dir1/dir1/file1.txt");
+ assertFalse(file.exists());
+ assertFalse(file.getParent().exists());
+ assertFalse(file.getParent().getParent().exists());
+ file.createFile();
+ assertTrue(file.exists());
+ assertSame(FileType.FILE, file.getType());
+ assertTrue(file.isFile());
+ assertEquals(0, file.getContent().getSize());
+ assertTrue(file.getParent().exists());
+ assertTrue(file.getParent().getParent().exists());
+ assertFalse(file.getParent().isHidden());
+ assertFalse(file.getParent().getParent().isHidden());
- assertSameContent(content, fileCopy);
+ // Test creating a file that already exists
+ assertTrue(file.exists());
+ file.createFile();
+ assertTrue(file.exists());
+ assertTrue(file.isReadable());
+ assertTrue(file.isWriteable());
}
/**
- * Tests create-delete-create-a-file sequence on the same file system.
+ * Tests file/folder creation with mismatched types.
*/
@Test
- public void testCreateDeleteCreateSameFileSystem() throws Exception {
+ public void testFileCreateMismatched() throws Exception {
final FileObject scratchFolder = createScratchFolder();
- // Create direct child of the test folder
- final FileObject file = scratchFolder.resolveFile("file1.txt");
- assertFalse(file.exists());
+ // Create a test file and folder
+ final FileObject file = scratchFolder.resolveFile("dir1/file1.txt");
+ file.createFile();
+ assertEquals(FileType.FILE, file.getType());
+ assertTrue(file.isFile());
- // Create the source file
- final String content = "Here is some sample content for the file. Blah Blah Blah.";
- try (OutputStream os = file.getContent().getOutputStream()) {
- os.write(content.getBytes(StandardCharsets.UTF_8));
+ final FileObject folder = scratchFolder.resolveFile("dir1/dir2");
+ folder.createFolder();
+ assertEquals(FileType.FOLDER, folder.getType());
+ assertTrue(folder.isFolder());
+
+ // Attempt to create a file that already exists as a folder
+ try {
+ folder.createFile();
+ fail();
+ } catch (final FileSystemException exc) {
}
- assertSameContent(content, file);
+ // Attempt to create a folder that already exists as a file
+ try {
+ file.createFolder();
+ fail();
+ } catch (final FileSystemException exc) {
+ }
- // Make sure we can copy the new file to another file on the same filesystem
- final FileObject fileCopy = scratchFolder.resolveFile("file1copy.txt");
- assertFalse(fileCopy.exists());
- fileCopy.copyFrom(file, Selectors.SELECT_SELF);
+ // Attempt to create a folder as a child of a file
+ final FileObject folder2 = file.resolveFile("some-child");
+ try {
+ folder2.createFolder();
+ fail();
+ } catch (final FileSystemException exc) {
+ }
+ }
- assertSameContent(content, fileCopy);
+ /**
+ * Tests folder creation.
+ */
+ @Test
+ public void testFolderCreate() throws Exception {
+ final FileObject scratchFolder = createScratchFolder();
- // Delete the file.
- assertTrue(fileCopy.exists());
- assertTrue(fileCopy.delete());
+ // Create direct child of the test folder
+ FileObject folder = scratchFolder.resolveFile("dir1");
+ assertFalse(folder.exists());
+ folder.createFolder();
+ assertTrue(folder.exists());
+ assertSame(FileType.FOLDER, folder.getType());
+ assertTrue(folder.isFolder());
+ assertEquals(0, folder.getChildren().length);
- // Make sure we can copy the same new file to the same target file on the same filesystem
- assertFalse(fileCopy.exists());
- fileCopy.copyFrom(file, Selectors.SELECT_SELF);
+ // Create a descendant, where the intermediate folders don't exist
+ folder = scratchFolder.resolveFile("dir2/dir1/dir1");
+ assertFalse(folder.exists());
+ assertFalse(folder.getParent().exists());
+ assertFalse(folder.getParent().getParent().exists());
+ folder.createFolder();
+ assertTrue(folder.exists());
+ assertSame(FileType.FOLDER, folder.getType());
+ assertTrue(folder.isFolder());
+ assertEquals(0, folder.getChildren().length);
+ assertTrue(folder.getParent().exists());
+ assertTrue(folder.getParent().getParent().exists());
- assertSameContent(content, fileCopy);
+ // Test creating a folder that already exists
+ assertTrue(folder.exists());
+ folder.createFolder();
}
/**
@@ -554,85 +636,62 @@ public class ProviderWriteTests extends AbstractProviderTestCase {
}
/**
- * Ensures the names of a set of files match an expected set.
+ * Tests overwriting a file on the same file system.
*/
- private void assertSameFileSet(final Set<String> names, final FileObject[] files) {
- // Make sure the sets are the same length
- assertEquals(names.size(), files.length);
+ @Test
+ public void testOverwriteSameFileSystem() throws Exception {
+ final FileObject scratchFolder = createScratchFolder();
- // Check for unexpected names
- for (final FileObject file : files) {
- assertTrue(names.contains(file.getName().getBaseName()));
+ // Create direct child of the test folder
+ final FileObject file = scratchFolder.resolveFile("file1.txt");
+ assertFalse(file.exists());
+
+ // Create the source file
+ final String content = "Here is some sample content for the file. Blah Blah Blah.";
+ try (OutputStream os = file.getContent().getOutputStream()) {
+ os.write(content.getBytes(StandardCharsets.UTF_8));
}
- }
- /**
- * A test listener.
- */
- private static class TestListener implements FileListener {
- private final FileObject file;
- private final ArrayList<Object> events = new ArrayList<>();
- private static final Object CREATE = "create";
- private static final Object DELETE = "delete";
- private static final Object CHANGED = "changed";
+ assertSameContent(content, file);
- public TestListener(final FileObject file) {
- this.file = file;
- }
+ // Make sure we can copy the new file to another file on the same file system
+ final FileObject fileCopy = scratchFolder.resolveFile("file1copy.txt");
+ assertFalse(fileCopy.exists());
+ file.getContent().write(fileCopy);
- /**
- * Called when a file is created.
- */
- @Override
- public void fileCreated(final FileChangeEvent event) {
- assertFalse("Unexpected create event", events.isEmpty());
- assertSame("Expecting a create event", CREATE, events.remove(0));
- assertEquals(Objects.toString(file), file, event.getFileObject());
- try {
- assertTrue(Objects.toString(file), file.exists());
- } catch (final FileSystemException e) {
- fail();
- }
- }
+ assertSameContent(content, fileCopy);
- /**
- * Called when a file is deleted.
- */
- @Override
- public void fileDeleted(final FileChangeEvent event) {
- assertFalse("Unexpected delete event", events.isEmpty());
- assertSame("Expecting a delete event", DELETE, events.remove(0));
- assertEquals(Objects.toString(file), file, event.getFileObject());
- try {
- assertFalse(Objects.toString(file), file.exists());
- } catch (final FileSystemException e) {
- fail();
- }
- }
+ // Make sure we can copy the same new file to the same target file on the same file system
+ assertTrue(fileCopy.exists());
+ file.getContent().write(fileCopy);
- @Override
- public void fileChanged(final FileChangeEvent event) throws Exception {
- assertFalse("Unexpected changed event", events.isEmpty());
- assertSame("Expecting a changed event", CHANGED, events.remove(0));
- assertEquals(Objects.toString(file), file, event.getFileObject());
- try {
- assertFalse(Objects.toString(file), file.exists());
- } catch (final FileSystemException e) {
- fail();
- }
- }
+ assertSameContent(content, fileCopy);
- public void addCreateEvent() {
- events.add(CREATE);
- }
+ // Make sure we can copy the same new file to the same target file on the same file system
+ assertTrue(fileCopy.exists());
+ file.getContent().write(fileCopy.getContent());
- public void addDeleteEvent() {
- events.add(DELETE);
+ assertSameContent(content, fileCopy);
+
+ // Make sure we can copy the same new file to the same target file on the same file system
+ assertTrue(fileCopy.exists());
+ OutputStream outputStream = fileCopy.getContent().getOutputStream();
+ try {
+ file.getContent().write(outputStream);
+ } finally {
+ outputStream.close();
}
+ assertSameContent(content, fileCopy);
- public void assertFinished() {
- assertEquals("Missing event", 0, events.size());
+ // Make sure we can copy the same new file to the same target file on the same file system
+ assertTrue(fileCopy.exists());
+ outputStream = fileCopy.getContent().getOutputStream();
+ try {
+ file.getContent().write(outputStream, 1234);
+ } finally {
+ outputStream.close();
}
+ assertSameContent(content, fileCopy);
}
/**
@@ -683,63 +742,4 @@ public class ProviderWriteTests extends AbstractProviderTestCase {
assertSameContent(expectedString, fileTarget);
}
- /**
- * Tests overwriting a file on the same file system.
- */
- @Test
- public void testOverwriteSameFileSystem() throws Exception {
- final FileObject scratchFolder = createScratchFolder();
-
- // Create direct child of the test folder
- final FileObject file = scratchFolder.resolveFile("file1.txt");
- assertFalse(file.exists());
-
- // Create the source file
- final String content = "Here is some sample content for the file. Blah Blah Blah.";
- try (OutputStream os = file.getContent().getOutputStream()) {
- os.write(content.getBytes(StandardCharsets.UTF_8));
- }
-
- assertSameContent(content, file);
-
- // Make sure we can copy the new file to another file on the same file system
- final FileObject fileCopy = scratchFolder.resolveFile("file1copy.txt");
- assertFalse(fileCopy.exists());
- file.getContent().write(fileCopy);
-
- assertSameContent(content, fileCopy);
-
- // Make sure we can copy the same new file to the same target file on the same file system
- assertTrue(fileCopy.exists());
- file.getContent().write(fileCopy);
-
- assertSameContent(content, fileCopy);
-
- // Make sure we can copy the same new file to the same target file on the same file system
- assertTrue(fileCopy.exists());
- file.getContent().write(fileCopy.getContent());
-
- assertSameContent(content, fileCopy);
-
- // Make sure we can copy the same new file to the same target file on the same file system
- assertTrue(fileCopy.exists());
- OutputStream outputStream = fileCopy.getContent().getOutputStream();
- try {
- file.getContent().write(outputStream);
- } finally {
- outputStream.close();
- }
- assertSameContent(content, fileCopy);
-
- // Make sure we can copy the same new file to the same target file on the same file system
- assertTrue(fileCopy.exists());
- outputStream = fileCopy.getContent().getOutputStream();
- try {
- file.getContent().write(outputStream, 1234);
- } finally {
- outputStream.close();
- }
- assertSameContent(content, fileCopy);
- }
-
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/RunTest.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/RunTest.java
index 512bed5..b9c306a 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/RunTest.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/RunTest.java
@@ -68,17 +68,6 @@ public class RunTest {
final TestResult result = new TestResult() {
@Override
- public void startTest(final Test test) {
- System.out.println("start " + test);
- System.out.flush();
- }
-
- @Override
- public void endTest(final Test test) {
- // System.err.println("end " + test);
- }
-
- @Override
public synchronized void addError(final Test test, final Throwable throwable) {
// throw new RuntimeException(throwable.getMessage());
throwable.printStackTrace();
@@ -89,6 +78,17 @@ public class RunTest {
// throw new RuntimeException(assertionFailedError.getMessage());
assertionFailedError.printStackTrace();
}
+
+ @Override
+ public void endTest(final Test test) {
+ // System.err.println("end " + test);
+ }
+
+ @Override
+ public void startTest(final Test test) {
+ System.out.println("start " + test);
+ System.out.flush();
+ }
};
for (int i = 0; i < tests.length; i++) {
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/VerifyingFileSelector.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/VerifyingFileSelector.java
index 09f8237..38170e7 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/VerifyingFileSelector.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/VerifyingFileSelector.java
@@ -44,6 +44,29 @@ public class VerifyingFileSelector extends Assert implements FileSelector {
}
/**
+ * Asserts that the selector has seen all the files.
+ *
+ * @return The files in the order they where visited.
+ */
+ public List<FileObject> finish() {
+ assertEquals(0, children.size());
+ return files;
+ }
+
+ /**
+ * Finds a child of the current folder.
+ */
+ private FileInfo getChild(final String baseName) {
+ if (currentFolderInfo == null) {
+ assertEquals(rootFile.baseName, baseName);
+ return rootFile;
+ }
+ final FileInfo child = currentFolderInfo.children.get(baseName);
+ assertNotNull("Could not locate child " + baseName, child);
+ return child;
+ }
+
+ /**
* Determines if a file or folder should be selected.
*/
@Override
@@ -100,27 +123,4 @@ public class VerifyingFileSelector extends Assert implements FileSelector {
return true;
}
-
- /**
- * Finds a child of the current folder.
- */
- private FileInfo getChild(final String baseName) {
- if (currentFolderInfo == null) {
- assertEquals(rootFile.baseName, baseName);
- return rootFile;
- }
- final FileInfo child = currentFolderInfo.children.get(baseName);
- assertNotNull("Could not locate child " + baseName, child);
- return child;
- }
-
- /**
- * Asserts that the selector has seen all the files.
- *
- * @return The files in the order they where visited.
- */
- public List<FileObject> finish() {
- assertEquals(0, children.size());
- return files;
- }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/cache/AbstractFilesCacheTestsBase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/cache/AbstractFilesCacheTestsBase.java
index 492cbef..a9a32cf 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/cache/AbstractFilesCacheTestsBase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/cache/AbstractFilesCacheTestsBase.java
@@ -32,24 +32,14 @@ import org.junit.Test;
*/
public abstract class AbstractFilesCacheTestsBase extends AbstractProviderTestCase {
- /**
- * Will test if the cache is cleared and if it is still useable afterwards. It will actually ensure the test is
- * hitting the cache.
- */
- @Test
- public void testClearFiles() throws Exception {
- final FilesCache cache = getManager().getFilesCache();
-
- final FileObject fo1 = getWriteFolder().resolveFile("dir1");
-
- // clean the cache for this file system
- cache.clear(fo1.getFileSystem());
- // make sure a empty cache clean does not fail
- cache.clear(fo1.getFileSystem());
-
- final FileObject fo2 = getWriteFolder().resolveFile("dir1");
+ /** Helper method, may be used in cache specific tests. */
+ protected int getFileHashCode() throws FileSystemException {
+ final FileObject fo = getWriteFolder().resolveFile("file2");
+ if (!fo.exists()) {
+ fo.createFile();
+ }
- assertNotSame("Objects after cache clear should be different", fo1, fo2);
+ return fo.hashCode();
}
/**
@@ -78,13 +68,23 @@ public abstract class AbstractFilesCacheTestsBase extends AbstractProviderTestCa
assertTrue(cache.putFileIfAbsent(fo));
}
- /** Helper method, may be used in cache specific tests. */
- protected int getFileHashCode() throws FileSystemException {
- final FileObject fo = getWriteFolder().resolveFile("file2");
- if (!fo.exists()) {
- fo.createFile();
- }
+ /**
+ * Will test if the cache is cleared and if it is still useable afterwards. It will actually ensure the test is
+ * hitting the cache.
+ */
+ @Test
+ public void testClearFiles() throws Exception {
+ final FilesCache cache = getManager().getFilesCache();
- return fo.hashCode();
+ final FileObject fo1 = getWriteFolder().resolveFile("dir1");
+
+ // clean the cache for this file system
+ cache.clear(fo1.getFileSystem());
+ // make sure a empty cache clean does not fail
+ cache.clear(fo1.getFileSystem());
+
+ final FileObject fo2 = getWriteFolder().resolveFile("dir1");
+
+ assertNotSame("Objects after cache clear should be different", fo1, fo2);
}
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/cache/LRUFilesCacheTests.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/cache/LRUFilesCacheTests.java
index 27dfa5a..af285d1 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/cache/LRUFilesCacheTests.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/cache/LRUFilesCacheTests.java
@@ -30,6 +30,15 @@ import org.junit.Test;
public class LRUFilesCacheTests extends AbstractFilesCacheTestsBase {
@Test
+ public void testClass() {
+ @SuppressWarnings("resource")
+ final DefaultFileSystemManager manager = getManager();
+ Assert.assertNotNull("manager", manager);
+ final FilesCache filesCache = manager.getFilesCache();
+ assertTrue(Objects.toString(filesCache), filesCache instanceof LRUFilesCache);
+ }
+
+ @Test
public void testFilesCache() throws Exception {
final FileObject scratchFolder = getWriteFolder();
Assert.assertNotNull("scratchFolder", scratchFolder);
@@ -73,13 +82,4 @@ public class LRUFilesCacheTests extends AbstractFilesCacheTestsBase {
final FileObject dir1_2 = scratchFolder.resolveFile("dir1");
assertNotSame(dir1, dir1_2);
}
-
- @Test
- public void testClass() {
- @SuppressWarnings("resource")
- final DefaultFileSystemManager manager = getManager();
- Assert.assertNotNull("manager", manager);
- final FilesCache filesCache = manager.getFilesCache();
- assertTrue(Objects.toString(filesCache), filesCache instanceof LRUFilesCache);
- }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/cache/NullFilesCacheTests.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/cache/NullFilesCacheTests.java
index 3b362e1..91f0b64 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/cache/NullFilesCacheTests.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/cache/NullFilesCacheTests.java
@@ -30,17 +30,6 @@ import org.junit.Test;
*/
public class NullFilesCacheTests extends AbstractFilesCacheTestsBase {
- @Test
- public void testFilesCache() throws Exception {
- final FileObject scratchFolder = getWriteFolder();
- Assert.assertNotNull("This test should not have a null FileObject scratch folder", scratchFolder);
-
- final FileObject dir1 = scratchFolder.resolveFile("dir1");
- final FileObject dir1_2 = scratchFolder.resolveFile("dir1");
-
- assertNotSame("Should always be new instance with NullCache", dir1, dir1_2);
- }
-
@Override
@Test
public void testBasicCacheOps() throws Exception {
@@ -71,4 +60,15 @@ public class NullFilesCacheTests extends AbstractFilesCacheTestsBase {
Assert.assertNotNull("This test should not have a null DefaultFileSystemManager", manager);
assertTrue(manager.getFilesCache() instanceof NullFilesCache);
}
+
+ @Test
+ public void testFilesCache() throws Exception {
+ final FileObject scratchFolder = getWriteFolder();
+ Assert.assertNotNull("This test should not have a null FileObject scratch folder", scratchFolder);
+
+ final FileObject dir1 = scratchFolder.resolveFile("dir1");
+ final FileObject dir1_2 = scratchFolder.resolveFile("dir1");
+
+ assertNotSame("Should always be new instance with NullCache", dir1, dir1_2);
+ }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/cache/WeakRefFilesCacheTests.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/cache/WeakRefFilesCacheTests.java
index ca9916b..2134767 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/cache/WeakRefFilesCacheTests.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/cache/WeakRefFilesCacheTests.java
@@ -25,6 +25,11 @@ import org.junit.Test;
public class WeakRefFilesCacheTests extends AbstractFilesCacheTestsBase {
@Test
+ public void testClass() {
+ assertTrue(getManager().getFilesCache() instanceof WeakRefFilesCache);
+ }
+
+ @Test
public void testFilesCache() throws Exception {
final FileObject scratchFolder = getWriteFolder();
@@ -34,9 +39,4 @@ public class WeakRefFilesCacheTests extends AbstractFilesCacheTestsBase {
// since both are still referenced they are not purged
assertSame(dir1, dir1_2);
}
-
- @Test
- public void testClass() {
- assertTrue(getManager().getFilesCache() instanceof WeakRefFilesCache);
- }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/AgeFileFilterTest.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/AgeFileFilterTest.java
index ecb396c..333e30b 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/AgeFileFilterTest.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/AgeFileFilterTest.java
@@ -62,6 +62,25 @@ public class AgeFileFilterTest extends BaseFilterTest {
private static FileObject zipFileObj;
+ @AfterClass
+ public static void afterClass() throws IOException {
+ newFileInfo = null;
+ newFile = null;
+
+ currentFileInfo = null;
+ currentFile = null;
+
+ oldFileInfo = null;
+ oldFile = null;
+
+ zipFileObj.close();
+ FileUtils.deleteQuietly(zipFile);
+ zipFile = null;
+
+ FileUtils.deleteDirectory(testDir);
+ testDir = null;
+ }
+
@BeforeClass
public static void beforeClass() throws IOException {
testDir = getTestDir(AgeFileFilterTest.class.getName());
@@ -91,25 +110,6 @@ public class AgeFileFilterTest extends BaseFilterTest {
}
- @AfterClass
- public static void afterClass() throws IOException {
- newFileInfo = null;
- newFile = null;
-
- currentFileInfo = null;
- currentFile = null;
-
- oldFileInfo = null;
- oldFile = null;
-
- zipFileObj.close();
- FileUtils.deleteQuietly(zipFile);
- zipFile = null;
-
- FileUtils.deleteDirectory(testDir);
- testDir = null;
- }
-
@Test
public void testAgeFileFilterDate() throws FileSystemException {
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/AndFileFilterTest.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/AndFileFilterTest.java
index c08f1da..f3da510 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/AndFileFilterTest.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/AndFileFilterTest.java
@@ -29,8 +29,85 @@ import org.junit.Test;
// CHECKSTYLE:OFF Test code
public class AndFileFilterTest extends BaseFilterTest {
+ /**
+ * Just a filter class.
+ */
+ private static class DummyFilter implements FileFilter {
+
+ @Override
+ public boolean accept(final FileSelectInfo fileSelectInfo) {
+ return false;
+ }
+
+ }
+
+ /**
+ * Always FALSE.
+ */
+ private static class False implements FileFilter {
+
+ @Override
+ public boolean accept(final FileSelectInfo fileSelectInfo) {
+ return false;
+ }
+
+ }
+
+ /**
+ * Always TRUE.
+ */
+ private static class True implements FileFilter {
+
+ @Override
+ public boolean accept(final FileSelectInfo fileSelectInfo) {
+ return true;
+ }
+
+ }
+
+ @SuppressWarnings("deprecation")
@Test
- public void testAndFileFilterFileFilter() {
+ public void testAccept() throws FileSystemException {
+
+ final FileSelectInfo any = createFileSelectInfo(new File("anyfile"));
+
+ // Empty
+ Assert.assertFalse(new AndFileFilter().accept(any));
+
+ // True
+ Assert.assertTrue(new AndFileFilter(new True()).accept(any));
+ Assert.assertTrue(new AndFileFilter(new True(), new True()).accept(any));
+
+ // False
+ Assert.assertFalse(new AndFileFilter(new False()).accept(any));
+ Assert.assertFalse(new AndFileFilter(new False(), new False()).accept(any));
+ Assert.assertFalse(new AndFileFilter(new False(), new True()).accept(any));
+ Assert.assertFalse(new AndFileFilter(new True(), new False()).accept(any));
+
+ }
+
+ @Test
+ public void testAcceptChecked() throws FileSystemException {
+
+ final FileSelectInfo any = createFileSelectInfo(new File("anyfile"));
+
+ // Empty
+ Assert.assertFalse(new AndFileFilter().accept(any));
+
+ // True
+ Assert.assertTrue(new AndFileFilter(new True()).accept(any));
+ Assert.assertTrue(new AndFileFilter(new True(), new True()).accept(any));
+
+ // False
+ Assert.assertFalse(new AndFileFilter(new False()).accept(any));
+ Assert.assertFalse(new AndFileFilter(new False(), new False()).accept(any));
+ Assert.assertFalse(new AndFileFilter(new False(), new True()).accept(any));
+ Assert.assertFalse(new AndFileFilter(new True(), new False()).accept(any));
+
+ }
+
+ @Test
+ public void testAddFileFilter() {
// PREPARE
final FileFilter filter1 = new DummyFilter();
@@ -38,7 +115,10 @@ public class AndFileFilterTest extends BaseFilterTest {
final FileFilter filter3 = new DummyFilter();
// TEST
- final AndFileFilter testee = new AndFileFilter(filter1, filter2, filter3);
+ final AndFileFilter testee = new AndFileFilter();
+ testee.addFileFilter(filter1);
+ testee.addFileFilter(filter2);
+ testee.addFileFilter(filter3);
// VERIFY
assertContainsOnly(testee.getFileFilters(), filter1, filter2, filter3);
@@ -46,19 +126,15 @@ public class AndFileFilterTest extends BaseFilterTest {
}
@Test
- public void testAndFileFilterList() {
+ public void testAndFileFilterFileFilter() {
// PREPARE
final FileFilter filter1 = new DummyFilter();
final FileFilter filter2 = new DummyFilter();
final FileFilter filter3 = new DummyFilter();
- final List<FileFilter> list = new ArrayList<>();
- list.add(filter1);
- list.add(filter2);
- list.add(filter3);
// TEST
- final AndFileFilter testee = new AndFileFilter(list);
+ final AndFileFilter testee = new AndFileFilter(filter1, filter2, filter3);
// VERIFY
assertContainsOnly(testee.getFileFilters(), filter1, filter2, filter3);
@@ -66,18 +142,19 @@ public class AndFileFilterTest extends BaseFilterTest {
}
@Test
- public void testAddFileFilter() {
+ public void testAndFileFilterList() {
// PREPARE
final FileFilter filter1 = new DummyFilter();
final FileFilter filter2 = new DummyFilter();
final FileFilter filter3 = new DummyFilter();
+ final List<FileFilter> list = new ArrayList<>();
+ list.add(filter1);
+ list.add(filter2);
+ list.add(filter3);
// TEST
- final AndFileFilter testee = new AndFileFilter();
- testee.addFileFilter(filter1);
- testee.addFileFilter(filter2);
- testee.addFileFilter(filter3);
+ final AndFileFilter testee = new AndFileFilter(list);
// VERIFY
assertContainsOnly(testee.getFileFilters(), filter1, filter2, filter3);
@@ -122,82 +199,5 @@ public class AndFileFilterTest extends BaseFilterTest {
}
- @SuppressWarnings("deprecation")
- @Test
- public void testAccept() throws FileSystemException {
-
- final FileSelectInfo any = createFileSelectInfo(new File("anyfile"));
-
- // Empty
- Assert.assertFalse(new AndFileFilter().accept(any));
-
- // True
- Assert.assertTrue(new AndFileFilter(new True()).accept(any));
- Assert.assertTrue(new AndFileFilter(new True(), new True()).accept(any));
-
- // False
- Assert.assertFalse(new AndFileFilter(new False()).accept(any));
- Assert.assertFalse(new AndFileFilter(new False(), new False()).accept(any));
- Assert.assertFalse(new AndFileFilter(new False(), new True()).accept(any));
- Assert.assertFalse(new AndFileFilter(new True(), new False()).accept(any));
-
- }
-
- @Test
- public void testAcceptChecked() throws FileSystemException {
-
- final FileSelectInfo any = createFileSelectInfo(new File("anyfile"));
-
- // Empty
- Assert.assertFalse(new AndFileFilter().accept(any));
-
- // True
- Assert.assertTrue(new AndFileFilter(new True()).accept(any));
- Assert.assertTrue(new AndFileFilter(new True(), new True()).accept(any));
-
- // False
- Assert.assertFalse(new AndFileFilter(new False()).accept(any));
- Assert.assertFalse(new AndFileFilter(new False(), new False()).accept(any));
- Assert.assertFalse(new AndFileFilter(new False(), new True()).accept(any));
- Assert.assertFalse(new AndFileFilter(new True(), new False()).accept(any));
-
- }
-
- /**
- * Just a filter class.
- */
- private static class DummyFilter implements FileFilter {
-
- @Override
- public boolean accept(final FileSelectInfo fileSelectInfo) {
- return false;
- }
-
- }
-
- /**
- * Always TRUE.
- */
- private static class True implements FileFilter {
-
- @Override
- public boolean accept(final FileSelectInfo fileSelectInfo) {
- return true;
- }
-
- }
-
- /**
- * Always FALSE.
- */
- private static class False implements FileFilter {
-
- @Override
- public boolean accept(final FileSelectInfo fileSelectInfo) {
- return false;
- }
-
- }
-
}
// CHECKSTYLE:ON
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/BaseFilterTest.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/BaseFilterTest.java
index 5c925d8..9eb5652 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/BaseFilterTest.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/BaseFilterTest.java
@@ -44,6 +44,72 @@ import org.junit.Assert;
public abstract class BaseFilterTest {
/**
+ * Verifies at least all given objects are in the list.
+ *
+ * @param list List to use.
+ * @param objects Objects to find.
+ */
+ protected static void assertContains(final List<?> list, final Object... objects) {
+ for (final Object obj : objects) {
+ Assert.assertTrue("Couldn't find " + obj + " in " + Arrays.asList(objects), list.indexOf(obj) > -1);
+ }
+ }
+
+ /**
+ * Verifies only the given objects are in the list.
+ *
+ * @param list List to scan.
+ * @param objects Objects to find.
+ */
+ protected static void assertContainsOnly(final List<?> list, final Object... objects) {
+ for (final Object obj : objects) {
+ Assert.assertTrue("Couldn't find " + obj + " in " + Arrays.asList(objects), list.indexOf(obj) > -1);
+ }
+ Assert.assertEquals(objects.length, list.size());
+ }
+
+ /**
+ * Concatenate a path and a file name taking {@code null} and empty string
+ * values into account.
+ *
+ * @param path Path - Can be {@code null} or an empty string.
+ * @param fileName Filename - Cannot be {@code null}.
+ * @param separator Separator for directories - Can be {@code null} or an
+ * empty string.
+ *
+ * @return Path and file name divided by the separator.
+ */
+ public static String concatPathAndFilename(final String path, final String fileName, final String separator) {
+
+ if (fileName == null) {
+ throw new IllegalArgumentException("file name cannot be null");
+ }
+ if (fileName.trim().isEmpty()) {
+ throw new IllegalArgumentException("file name cannot be empty");
+ }
+ if (separator == null) {
+ throw new IllegalArgumentException("separator cannot be null");
+ }
+ if (separator.trim().isEmpty()) {
+ throw new IllegalArgumentException("separator cannot be empty");
+ }
+
+ if (path == null) {
+ return fileName;
+ }
+ final String trimmedPath = path.trim();
+ if (trimmedPath.isEmpty()) {
+ return fileName;
+ }
+ final String trimmedFilename = fileName.trim();
+ if (trimmedPath.endsWith(separator)) {
+ return trimmedPath + trimmedFilename;
+ }
+ return trimmedPath + separator + trimmedFilename;
+
+ }
+
+ /**
* Creates a file select info object for the given file.
*
* @param file File to create an info for.
@@ -55,8 +121,12 @@ public abstract class BaseFilterTest {
final FileObject fileObject = fsManager.toFileObject(file);
return new FileSelectInfo() {
@Override
- public FileObject getFile() {
- return fileObject;
+ public FileObject getBaseFolder() {
+ try {
+ return fileObject.getParent();
+ } catch (final FileSystemException ex) {
+ throw new RuntimeException(ex);
+ }
}
@Override
@@ -65,12 +135,8 @@ public abstract class BaseFilterTest {
}
@Override
- public FileObject getBaseFolder() {
- try {
- return fileObject.getParent();
- } catch (final FileSystemException ex) {
- throw new RuntimeException(ex);
- }
+ public FileObject getFile() {
+ return fileObject;
}
@Override
@@ -84,44 +150,6 @@ public abstract class BaseFilterTest {
}
/**
- * Returns a ZIP file object.
- *
- * @param file File to resolve.
- *
- * @return File object.
- *
- * @throws FileSystemException Error resolving the file.
- */
- protected static FileObject getZipFileObject(final File file) throws FileSystemException {
- final FileSystemManager fsManager = VFS.getManager();
- return fsManager.resolveFile("zip:" + file.toURI());
- }
-
- /**
- * Asserts that the array contains the given file names.
- *
- * @param files Array to check.
- * @param fileNames names File names to find.
- */
- protected void assertContains(final FileObject[] files, final String... fileNames) {
- for (final String fileName : fileNames) {
- if (!find(files, fileName)) {
- fail("File '" + fileName + "' not found in: " + Arrays.asList(files));
- }
- }
- }
-
- private boolean find(final FileObject[] files, final String fileName) {
- for (final FileObject file : files) {
- final String name = file.getName().getBaseName();
- if (name.equals(fileName)) {
- return true;
- }
- }
- return false;
- }
-
- /**
* Returns the temporary directory.
*
* @return java.io.tmpdir
@@ -142,78 +170,37 @@ public abstract class BaseFilterTest {
}
/**
- * Verifies at least all given objects are in the list.
- *
- * @param list List to use.
- * @param objects Objects to find.
- */
- protected static void assertContains(final List<?> list, final Object... objects) {
- for (final Object obj : objects) {
- Assert.assertTrue("Couldn't find " + obj + " in " + Arrays.asList(objects), list.indexOf(obj) > -1);
- }
- }
-
- /**
- * Verifies only the given objects are in the list.
+ * Returns a ZIP file object.
*
- * @param list List to scan.
- * @param objects Objects to find.
- */
- protected static void assertContainsOnly(final List<?> list, final Object... objects) {
- for (final Object obj : objects) {
- Assert.assertTrue("Couldn't find " + obj + " in " + Arrays.asList(objects), list.indexOf(obj) > -1);
- }
- Assert.assertEquals(objects.length, list.size());
- }
-
- /**
- * Adds a file to a ZIP output stream.
+ * @param file File to resolve.
*
- * @param srcFile File to add - Cannot be {@code null}.
- * @param destPath Path to use for the file - May be {@code null} or empty.
- * @param out Destination stream - Cannot be {@code null}.
+ * @return File object.
*
- * @throws IOException Error writing to the output stream.
+ * @throws FileSystemException Error resolving the file.
*/
- private static void zipFile(final File srcFile, final String destPath, final ZipOutputStream out)
- throws IOException {
-
- final byte[] buf = new byte[1024];
- try (final InputStream in = new BufferedInputStream(Files.newInputStream(srcFile.toPath()))) {
- final ZipEntry zipEntry = new ZipEntry(concatPathAndFilename(destPath, srcFile.getName(), File.separator));
- zipEntry.setTime(srcFile.lastModified());
- out.putNextEntry(zipEntry);
- int len;
- while ((len = in.read(buf)) > 0) {
- out.write(buf, 0, len);
- }
- out.closeEntry();
- }
+ protected static FileObject getZipFileObject(final File file) throws FileSystemException {
+ final FileSystemManager fsManager = VFS.getManager();
+ return fsManager.resolveFile("zip:" + file.toURI());
}
/**
- * Add a directory to a ZIP output stream.
+ * List all files for a directory.
*
- * @param srcDir Directory to add - Cannot be {@code null} and must be a
- * valid directory.
- * @param filter Filter or {@code null} for all files.
- * @param destPath Path to use for the ZIP archive - May be {@code null} or
- * an empyt string.
- * @param out Destination stream - Cannot be {@code null}.
+ * @param srcDir Directory to list the files for - Cannot be {@code null}
+ * and must be a valid directory.
+ * @param filter Filter or {@code null} for all files.
*
- * @throws IOException Error writing to the output stream.
+ * @return List of child entries of the directory.
*/
- private static void zipDir(final File srcDir, final FileFilter filter, final String destPath,
- final ZipOutputStream out) throws IOException {
+ private static File[] listFiles(final File srcDir, final FileFilter filter) {
- final File[] files = listFiles(srcDir, filter);
- for (final File file : files) {
- if (file.isDirectory()) {
- zipDir(file, filter, concatPathAndFilename(destPath, file.getName(), File.separator), out);
- } else {
- zipFile(file, destPath, out);
- }
+ final File[] files;
+ if (filter == null) {
+ files = srcDir.listFiles();
+ } else {
+ files = srcDir.listFiles(filter);
}
+ return files;
}
@@ -254,6 +241,32 @@ public abstract class BaseFilterTest {
}
/**
+ * Add a directory to a ZIP output stream.
+ *
+ * @param srcDir Directory to add - Cannot be {@code null} and must be a
+ * valid directory.
+ * @param filter Filter or {@code null} for all files.
+ * @param destPath Path to use for the ZIP archive - May be {@code null} or
+ * an empyt string.
+ * @param out Destination stream - Cannot be {@code null}.
+ *
+ * @throws IOException Error writing to the output stream.
+ */
+ private static void zipDir(final File srcDir, final FileFilter filter, final String destPath,
+ final ZipOutputStream out) throws IOException {
+
+ final File[] files = listFiles(srcDir, filter);
+ for (final File file : files) {
+ if (file.isDirectory()) {
+ zipDir(file, filter, concatPathAndFilename(destPath, file.getName(), File.separator), out);
+ } else {
+ zipFile(file, destPath, out);
+ }
+ }
+
+ }
+
+ /**
* Creates a ZIP file and adds all files in a directory and all it's sub
* directories to the archive.
*
@@ -272,65 +285,52 @@ public abstract class BaseFilterTest {
}
/**
- * Concatenate a path and a file name taking {@code null} and empty string
- * values into account.
+ * Adds a file to a ZIP output stream.
*
- * @param path Path - Can be {@code null} or an empty string.
- * @param fileName Filename - Cannot be {@code null}.
- * @param separator Separator for directories - Can be {@code null} or an
- * empty string.
+ * @param srcFile File to add - Cannot be {@code null}.
+ * @param destPath Path to use for the file - May be {@code null} or empty.
+ * @param out Destination stream - Cannot be {@code null}.
*
- * @return Path and file name divided by the separator.
+ * @throws IOException Error writing to the output stream.
*/
- public static String concatPathAndFilename(final String path, final String fileName, final String separator) {
-
- if (fileName == null) {
- throw new IllegalArgumentException("file name cannot be null");
- }
- if (fileName.trim().isEmpty()) {
- throw new IllegalArgumentException("file name cannot be empty");
- }
- if (separator == null) {
- throw new IllegalArgumentException("separator cannot be null");
- }
- if (separator.trim().isEmpty()) {
- throw new IllegalArgumentException("separator cannot be empty");
- }
+ private static void zipFile(final File srcFile, final String destPath, final ZipOutputStream out)
+ throws IOException {
- if (path == null) {
- return fileName;
- }
- final String trimmedPath = path.trim();
- if (trimmedPath.isEmpty()) {
- return fileName;
- }
- final String trimmedFilename = fileName.trim();
- if (trimmedPath.endsWith(separator)) {
- return trimmedPath + trimmedFilename;
+ final byte[] buf = new byte[1024];
+ try (final InputStream in = new BufferedInputStream(Files.newInputStream(srcFile.toPath()))) {
+ final ZipEntry zipEntry = new ZipEntry(concatPathAndFilename(destPath, srcFile.getName(), File.separator));
+ zipEntry.setTime(srcFile.lastModified());
+ out.putNextEntry(zipEntry);
+ int len;
+ while ((len = in.read(buf)) > 0) {
+ out.write(buf, 0, len);
+ }
+ out.closeEntry();
}
- return trimmedPath + separator + trimmedFilename;
-
}
/**
- * List all files for a directory.
- *
- * @param srcDir Directory to list the files for - Cannot be {@code null}
- * and must be a valid directory.
- * @param filter Filter or {@code null} for all files.
+ * Asserts that the array contains the given file names.
*
- * @return List of child entries of the directory.
+ * @param files Array to check.
+ * @param fileNames names File names to find.
*/
- private static File[] listFiles(final File srcDir, final FileFilter filter) {
-
- final File[] files;
- if (filter == null) {
- files = srcDir.listFiles();
- } else {
- files = srcDir.listFiles(filter);
+ protected void assertContains(final FileObject[] files, final String... fileNames) {
+ for (final String fileName : fileNames) {
+ if (!find(files, fileName)) {
+ fail("File '" + fileName + "' not found in: " + Arrays.asList(files));
+ }
}
- return files;
+ }
+ private boolean find(final FileObject[] files, final String fileName) {
+ for (final FileObject file : files) {
+ final String name = file.getName().getBaseName();
+ if (name.equals(fileName)) {
+ return true;
+ }
+ }
+ return false;
}
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/CanExecuteFileFilterTest.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/CanExecuteFileFilterTest.java
index 9139ee5..24bdc43 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/CanExecuteFileFilterTest.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/CanExecuteFileFilterTest.java
@@ -58,6 +58,29 @@ public class CanExecuteFileFilterTest extends BaseFilterTest {
private static FileObject zipFileObj;
+ @AfterClass
+ public static void afterClass() throws IOException {
+
+ executableFileInfo = null;
+ executableFile.delete();
+ executableFile = null;
+
+ notExecutableFileInfo = null;
+ notExecutableFile.delete();
+ notExecutableFile = null;
+
+ notExistingFileInfo = null;
+ notExistingFile = null;
+
+ zipFileObj.close();
+ FileUtils.deleteQuietly(zipFile);
+ zipFile = null;
+
+ FileUtils.deleteDirectory(testDir);
+ testDir = null;
+
+ }
+
@BeforeClass
public static void beforeClass() throws IOException {
@@ -82,29 +105,6 @@ public class CanExecuteFileFilterTest extends BaseFilterTest {
}
- @AfterClass
- public static void afterClass() throws IOException {
-
- executableFileInfo = null;
- executableFile.delete();
- executableFile = null;
-
- notExecutableFileInfo = null;
- notExecutableFile.delete();
- notExecutableFile = null;
-
- notExistingFileInfo = null;
- notExistingFile = null;
-
- zipFileObj.close();
- FileUtils.deleteQuietly(zipFile);
- zipFile = null;
-
- FileUtils.deleteDirectory(testDir);
- testDir = null;
-
- }
-
@Test
public void testAcceptCanExecute() throws FileSystemException {
Assert.assertTrue(CanExecuteFileFilter.CAN_EXECUTE.accept(executableFileInfo));
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/CanReadFileFilterTest.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/CanReadFileFilterTest.java
index cbfb592..f20203c 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/CanReadFileFilterTest.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/CanReadFileFilterTest.java
@@ -57,6 +57,29 @@ public class CanReadFileFilterTest extends BaseFilterTest {
private static FileObject zipFileObj;
+ @AfterClass
+ public static void afterClass() throws IOException {
+
+ writableFileInfo = null;
+ writableFile.delete();
+ writableFile = null;
+
+ readOnlyFileInfo = null;
+ readOnlyFile.delete();
+ readOnlyFile = null;
+
+ notExistingFileInfo = null;
+ notExistingFile = null;
+
+ zipFileObj.close();
+ FileUtils.deleteQuietly(zipFile);
+ zipFile = null;
+
+ FileUtils.deleteDirectory(testDir);
+ testDir = null;
+
+ }
+
@BeforeClass
public static void beforeClass() throws IOException {
@@ -81,26 +104,12 @@ public class CanReadFileFilterTest extends BaseFilterTest {
}
- @AfterClass
- public static void afterClass() throws IOException {
-
- writableFileInfo = null;
- writableFile.delete();
- writableFile = null;
-
- readOnlyFileInfo = null;
- readOnlyFile.delete();
- readOnlyFile = null;
-
- notExistingFileInfo = null;
- notExistingFile = null;
-
- zipFileObj.close();
- FileUtils.deleteQuietly(zipFile);
- zipFile = null;
+ @Test
+ public void testAcceptCannotRead() throws FileSystemException {
- FileUtils.deleteDirectory(testDir);
- testDir = null;
+ Assert.assertFalse(CanReadFileFilter.CANNOT_READ.accept(writableFileInfo));
+ Assert.assertFalse(CanReadFileFilter.CANNOT_READ.accept(readOnlyFileInfo));
+ Assert.assertTrue(CanReadFileFilter.CANNOT_READ.accept(notExistingFileInfo));
}
@@ -114,15 +123,6 @@ public class CanReadFileFilterTest extends BaseFilterTest {
}
@Test
- public void testAcceptCannotRead() throws FileSystemException {
-
- Assert.assertFalse(CanReadFileFilter.CANNOT_READ.accept(writableFileInfo));
- Assert.assertFalse(CanReadFileFilter.CANNOT_READ.accept(readOnlyFileInfo));
- Assert.assertTrue(CanReadFileFilter.CANNOT_READ.accept(notExistingFileInfo));
-
- }
-
- @Test
public void testAcceptReadOnly() throws FileSystemException {
Assert.assertFalse(CanReadFileFilter.READ_ONLY.accept(writableFileInfo));
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/CanWriteFileFilterTest.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/CanWriteFileFilterTest.java
index 744fa8b..453d819 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/CanWriteFileFilterTest.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/CanWriteFileFilterTest.java
@@ -57,6 +57,29 @@ public class CanWriteFileFilterTest extends BaseFilterTest {
private static FileObject zipFileObj;
+ @AfterClass
+ public static void afterClass() throws IOException {
+
+ writableFileInfo = null;
+ writableFile.delete();
+ writableFile = null;
+
+ readOnlyFileInfo = null;
+ readOnlyFile.delete();
+ readOnlyFile = null;
+
+ notExistingFileInfo = null;
+ notExistingFile = null;
+
+ zipFileObj.close();
+ FileUtils.deleteQuietly(zipFile);
+ zipFile = null;
+
+ FileUtils.deleteDirectory(testDir);
+ testDir = null;
+
+ }
+
@BeforeClass
public static void beforeClass() throws IOException {
@@ -81,26 +104,12 @@ public class CanWriteFileFilterTest extends BaseFilterTest {
}
- @AfterClass
- public static void afterClass() throws IOException {
-
- writableFileInfo = null;
- writableFile.delete();
- writableFile = null;
-
- readOnlyFileInfo = null;
- readOnlyFile.delete();
- readOnlyFile = null;
-
- notExistingFileInfo = null;
- notExistingFile = null;
-
- zipFileObj.close();
- FileUtils.deleteQuietly(zipFile);
- zipFile = null;
+ @Test
+ public void testAcceptCannotWrite() throws FileSystemException {
- FileUtils.deleteDirectory(testDir);
- testDir = null;
+ Assert.assertFalse(CanWriteFileFilter.CANNOT_WRITE.accept(writableFileInfo));
+ Assert.assertTrue(CanWriteFileFilter.CANNOT_WRITE.accept(readOnlyFileInfo));
+ Assert.assertFalse(CanWriteFileFilter.CANNOT_WRITE.accept(notExistingFileInfo));
}
@@ -114,15 +123,6 @@ public class CanWriteFileFilterTest extends BaseFilterTest {
}
@Test
- public void testAcceptCannotWrite() throws FileSystemException {
-
- Assert.assertFalse(CanWriteFileFilter.CANNOT_WRITE.accept(writableFileInfo));
- Assert.assertTrue(CanWriteFileFilter.CANNOT_WRITE.accept(readOnlyFileInfo));
- Assert.assertFalse(CanWriteFileFilter.CANNOT_WRITE.accept(notExistingFileInfo));
-
- }
-
- @Test
public void testAcceptZipFile() throws FileSystemException {
FileObject[] files;
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/DirectoryAndFileFilterTest.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/DirectoryAndFileFilterTest.java
index 334028b..6525082 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/DirectoryAndFileFilterTest.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/DirectoryAndFileFilterTest.java
@@ -59,29 +59,6 @@ public class DirectoryAndFileFilterTest extends BaseFilterTest {
private static FileObject zipFileObj;
- @BeforeClass
- public static void beforeClass() throws IOException {
-
- testDir = getTestDir(DirectoryAndFileFilterTest.class.getName());
- testDir.mkdir();
-
- dir = new File(testDir, DIR);
- dir.mkdir();
- dirInfo = createFileSelectInfo(dir);
-
- file = new File(dir, FILE);
- FileUtils.touch(file);
- fileInfo = createFileSelectInfo(file);
-
- notExistingFile = new File(testDir, "not-existing-file.txt");
- notExistingFileInfo = createFileSelectInfo(notExistingFile);
-
- zipFile = new File(getTempDir(), DirectoryAndFileFilterTest.class.getName() + ".zip");
- zipDir(testDir, "", zipFile);
- zipFileObj = getZipFileObject(zipFile);
-
- }
-
@AfterClass
public static void afterClass() throws IOException {
@@ -104,25 +81,26 @@ public class DirectoryAndFileFilterTest extends BaseFilterTest {
}
- @Test
- public void testDirectoryFileFilter() throws FileSystemException {
-
- final FileFilter testee = DirectoryFileFilter.DIRECTORY;
+ @BeforeClass
+ public static void beforeClass() throws IOException {
- Assert.assertTrue(testee.accept(dirInfo));
- Assert.assertFalse(testee.accept(fileInfo));
- Assert.assertFalse(testee.accept(notExistingFileInfo));
+ testDir = getTestDir(DirectoryAndFileFilterTest.class.getName());
+ testDir.mkdir();
- }
+ dir = new File(testDir, DIR);
+ dir.mkdir();
+ dirInfo = createFileSelectInfo(dir);
- @Test
- public void testFileFileFilter() throws FileSystemException {
+ file = new File(dir, FILE);
+ FileUtils.touch(file);
+ fileInfo = createFileSelectInfo(file);
- final FileFilter testee = FileFileFilter.FILE;
+ notExistingFile = new File(testDir, "not-existing-file.txt");
+ notExistingFileInfo = createFileSelectInfo(notExistingFile);
- Assert.assertTrue(testee.accept(fileInfo));
- Assert.assertFalse(testee.accept(dirInfo));
- Assert.assertFalse(testee.accept(notExistingFileInfo));
+ zipFile = new File(getTempDir(), DirectoryAndFileFilterTest.class.getName() + ".zip");
+ zipDir(testDir, "", zipFile);
+ zipFileObj = getZipFileObject(zipFile);
}
@@ -134,13 +112,13 @@ public class DirectoryAndFileFilterTest extends BaseFilterTest {
// FILE Filter
files = zipFileObj.findFiles(new FileSelector() {
@Override
- public boolean traverseDescendents(final FileSelectInfo fileInfo) throws Exception {
- return true;
+ public boolean includeFile(final FileSelectInfo fileInfo) throws Exception {
+ return FileFileFilter.FILE.accept(fileInfo);
}
@Override
- public boolean includeFile(final FileSelectInfo fileInfo) throws Exception {
- return FileFileFilter.FILE.accept(fileInfo);
+ public boolean traverseDescendents(final FileSelectInfo fileInfo) throws Exception {
+ return true;
}
});
assertContains(files, FILE);
@@ -153,5 +131,27 @@ public class DirectoryAndFileFilterTest extends BaseFilterTest {
}
+ @Test
+ public void testDirectoryFileFilter() throws FileSystemException {
+
+ final FileFilter testee = DirectoryFileFilter.DIRECTORY;
+
+ Assert.assertTrue(testee.accept(dirInfo));
+ Assert.assertFalse(testee.accept(fileInfo));
+ Assert.assertFalse(testee.accept(notExistingFileInfo));
+
+ }
+
+ @Test
+ public void testFileFileFilter() throws FileSystemException {
+
+ final FileFilter testee = FileFileFilter.FILE;
+
+ Assert.assertTrue(testee.accept(fileInfo));
+ Assert.assertFalse(testee.accept(dirInfo));
+ Assert.assertFalse(testee.accept(notExistingFileInfo));
+
+ }
+
}
// CHECKSTYLE:ON
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/EmptyFileFilterTest.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/EmptyFileFilterTest.java
index 7b79560..9d94ebf 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/EmptyFileFilterTest.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/EmptyFileFilterTest.java
@@ -62,6 +62,28 @@ public class EmptyFileFilterTest extends BaseFilterTest {
private static FileObject zipFileObj;
+ @AfterClass
+ public static void afterClass() throws IOException {
+
+ notEmptyFile = null;
+ notEmptyFileInfo = null;
+ emptyFile = null;
+ emptyFileInfo = null;
+ notEmptyDir = null;
+ notEmptyDirInfo = null;
+ emptyDir = null;
+ emptyDirInfo = null;
+ notExistingFile = null;
+ notExistingFileInfo = null;
+
+ zipFileObj.close();
+ FileUtils.deleteQuietly(zipFile);
+ zipFile = null;
+
+ FileUtils.deleteDirectory(testDir);
+ testDir = null;
+ }
+
@BeforeClass
public static void beforeClass() throws IOException {
testDir = getTestDir(EmptyFileFilterTest.class.getName());
@@ -94,28 +116,6 @@ public class EmptyFileFilterTest extends BaseFilterTest {
}
- @AfterClass
- public static void afterClass() throws IOException {
-
- notEmptyFile = null;
- notEmptyFileInfo = null;
- emptyFile = null;
- emptyFileInfo = null;
- notEmptyDir = null;
- notEmptyDirInfo = null;
- emptyDir = null;
- emptyDirInfo = null;
- notExistingFile = null;
- notExistingFileInfo = null;
-
- zipFileObj.close();
- FileUtils.deleteQuietly(zipFile);
- zipFile = null;
-
- FileUtils.deleteDirectory(testDir);
- testDir = null;
- }
-
@Test
public void testAcceptEmpty() throws FileSystemException {
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/HiddenFileFilterTest.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/HiddenFileFilterTest.java
index f3f7825..30d59c9 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/HiddenFileFilterTest.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/HiddenFileFilterTest.java
@@ -54,6 +54,24 @@ public class HiddenFileFilterTest extends BaseFilterTest {
private static FileObject zipFileObj;
+ @AfterClass
+ public static void afterClass() throws IOException {
+
+ visibleFile = null;
+ visibleFileInfo = null;
+ hiddenFile = null;
+ hiddenFileInfo = null;
+ notExistingFile = null;
+ notExistingFileInfo = null;
+
+ zipFileObj.close();
+ FileUtils.deleteQuietly(zipFile);
+ zipFile = null;
+
+ FileUtils.deleteDirectory(testDir);
+ testDir = null;
+ }
+
@BeforeClass
public static void beforeClass() throws IOException {
testDir = getTestDir(HiddenFileFilterTest.class.getName());
@@ -78,24 +96,6 @@ public class HiddenFileFilterTest extends BaseFilterTest {
}
- @AfterClass
- public static void afterClass() throws IOException {
-
- visibleFile = null;
- visibleFileInfo = null;
- hiddenFile = null;
- hiddenFileInfo = null;
- notExistingFile = null;
- notExistingFileInfo = null;
-
- zipFileObj.close();
- FileUtils.deleteQuietly(zipFile);
- zipFile = null;
-
- FileUtils.deleteDirectory(testDir);
- testDir = null;
- }
-
@Test
public void testAcceptHidden() throws FileSystemException {
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/OrFileFilterTest.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/OrFileFilterTest.java
index b5af949..50b7925 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/OrFileFilterTest.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/OrFileFilterTest.java
@@ -29,8 +29,64 @@ import org.junit.Test;
// CHECKSTYLE:OFF Test code
public class OrFileFilterTest extends BaseFilterTest {
+ /**
+ * Just a filter class.
+ */
+ private static class DummyFilter implements FileFilter {
+
+ @Override
+ public boolean accept(final FileSelectInfo fileInfo) {
+ return false;
+ }
+
+ }
+
+ /**
+ * Always FALSE.
+ */
+ private static class False implements FileFilter {
+
+ @Override
+ public boolean accept(final FileSelectInfo fileInfo) {
+ return false;
+ }
+
+ }
+
+ /**
+ * Always TRUE.
+ */
+ private static class True implements FileFilter {
+
+ @Override
+ public boolean accept(final FileSelectInfo fileInfo) {
+ return true;
+ }
+
+ }
+
@Test
- public void testOrFileFilterFileFilter() {
+ public void testAccept() throws FileSystemException {
+
+ final FileSelectInfo any = createFileSelectInfo(new File("anyfile"));
+
+ // Empty
+ Assert.assertFalse(new OrFileFilter().accept(any));
+
+ // True
+ Assert.assertTrue(new OrFileFilter(new True()).accept(any));
+ Assert.assertTrue(new OrFileFilter(new True(), new True()).accept(any));
+ Assert.assertTrue(new OrFileFilter(new False(), new True()).accept(any));
+ Assert.assertTrue(new OrFileFilter(new True(), new False()).accept(any));
+
+ // False
+ Assert.assertFalse(new OrFileFilter(new False()).accept(any));
+ Assert.assertFalse(new OrFileFilter(new False(), new False()).accept(any));
+
+ }
+
+ @Test
+ public void testAddFileFilter() {
// PREPARE
final FileFilter filter1 = new DummyFilter();
@@ -38,7 +94,10 @@ public class OrFileFilterTest extends BaseFilterTest {
final FileFilter filter3 = new DummyFilter();
// TEST
- final OrFileFilter testee = new OrFileFilter(filter1, filter2, filter3);
+ final OrFileFilter testee = new OrFileFilter();
+ testee.addFileFilter(filter1);
+ testee.addFileFilter(filter2);
+ testee.addFileFilter(filter3);
// VERIFY
assertContainsOnly(testee.getFileFilters(), filter1, filter2, filter3);
@@ -46,19 +105,15 @@ public class OrFileFilterTest extends BaseFilterTest {
}
@Test
- public void testOrFileFilterList() {
+ public void testOrFileFilterFileFilter() {
// PREPARE
final FileFilter filter1 = new DummyFilter();
final FileFilter filter2 = new DummyFilter();
final FileFilter filter3 = new DummyFilter();
- final List<FileFilter> list = new ArrayList<>();
- list.add(filter1);
- list.add(filter2);
- list.add(filter3);
// TEST
- final OrFileFilter testee = new OrFileFilter(list);
+ final OrFileFilter testee = new OrFileFilter(filter1, filter2, filter3);
// VERIFY
assertContainsOnly(testee.getFileFilters(), filter1, filter2, filter3);
@@ -66,18 +121,19 @@ public class OrFileFilterTest extends BaseFilterTest {
}
@Test
- public void testAddFileFilter() {
+ public void testOrFileFilterList() {
// PREPARE
final FileFilter filter1 = new DummyFilter();
final FileFilter filter2 = new DummyFilter();
final FileFilter filter3 = new DummyFilter();
+ final List<FileFilter> list = new ArrayList<>();
+ list.add(filter1);
+ list.add(filter2);
+ list.add(filter3);
// TEST
- final OrFileFilter testee = new OrFileFilter();
- testee.addFileFilter(filter1);
- testee.addFileFilter(filter2);
- testee.addFileFilter(filter3);
+ final OrFileFilter testee = new OrFileFilter(list);
// VERIFY
assertContainsOnly(testee.getFileFilters(), filter1, filter2, filter3);
@@ -122,61 +178,5 @@ public class OrFileFilterTest extends BaseFilterTest {
}
- @Test
- public void testAccept() throws FileSystemException {
-
- final FileSelectInfo any = createFileSelectInfo(new File("anyfile"));
-
- // Empty
- Assert.assertFalse(new OrFileFilter().accept(any));
-
- // True
- Assert.assertTrue(new OrFileFilter(new True()).accept(any));
- Assert.assertTrue(new OrFileFilter(new True(), new True()).accept(any));
- Assert.assertTrue(new OrFileFilter(new False(), new True()).accept(any));
- Assert.assertTrue(new OrFileFilter(new True(), new False()).accept(any));
-
- // False
- Assert.assertFalse(new OrFileFilter(new False()).accept(any));
- Assert.assertFalse(new OrFileFilter(new False(), new False()).accept(any));
-
- }
-
- /**
- * Just a filter class.
- */
- private static class DummyFilter implements FileFilter {
-
- @Override
- public boolean accept(final FileSelectInfo fileInfo) {
- return false;
- }
-
- }
-
- /**
- * Always TRUE.
- */
- private static class True implements FileFilter {
-
- @Override
- public boolean accept(final FileSelectInfo fileInfo) {
- return true;
- }
-
- }
-
- /**
- * Always FALSE.
- */
- private static class False implements FileFilter {
-
- @Override
- public boolean accept(final FileSelectInfo fileInfo) {
- return false;
- }
-
- }
-
}
// CHECKSTYLE:ON
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/RegexFileFilterTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/RegexFileFilterTestCase.java
index 789d115..f8feda3 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/RegexFileFilterTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/RegexFileFilterTestCase.java
@@ -32,6 +32,16 @@ import org.junit.Test;
public class RegexFileFilterTestCase extends BaseFilterTest {
@Test
+ public void testPatternNullArgConstruction() {
+ try {
+ new RegexFileFilter((Pattern) null);
+ fail();
+ } catch (final IllegalArgumentException ex) {
+ Assert.assertEquals(RegexFileFilter.PATTERN_IS_MISSING, ex.getMessage());
+ }
+ }
+
+ @Test
public void testRegex() throws Exception {
FileFilter filter;
@@ -64,9 +74,9 @@ public class RegexFileFilterTestCase extends BaseFilterTest {
}
@Test
- public void testStringNullArgConstruction() {
+ public void testStringIOCaseNullArgConstruction() {
try {
- new RegexFileFilter((String) null);
+ new RegexFileFilter((String) null, IOCase.INSENSITIVE);
fail();
} catch (final IllegalArgumentException ex) {
Assert.assertEquals(RegexFileFilter.PATTERN_IS_MISSING, ex.getMessage());
@@ -74,9 +84,9 @@ public class RegexFileFilterTestCase extends BaseFilterTest {
}
@Test
- public void testPatternNullArgConstruction() {
+ public void testStringNullArgConstruction() {
try {
- new RegexFileFilter((Pattern) null);
+ new RegexFileFilter((String) null);
fail();
} catch (final IllegalArgumentException ex) {
Assert.assertEquals(RegexFileFilter.PATTERN_IS_MISSING, ex.getMessage());
@@ -93,15 +103,5 @@ public class RegexFileFilterTestCase extends BaseFilterTest {
}
}
- @Test
- public void testStringIOCaseNullArgConstruction() {
- try {
- new RegexFileFilter((String) null, IOCase.INSENSITIVE);
- fail();
- } catch (final IllegalArgumentException ex) {
- Assert.assertEquals(RegexFileFilter.PATTERN_IS_MISSING, ex.getMessage());
- }
- }
-
}
// CHECKSTYLE:ON
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/SizeFileFilterTest.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/SizeFileFilterTest.java
index ca37942..d538f3a 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/SizeFileFilterTest.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/SizeFileFilterTest.java
@@ -53,6 +53,26 @@ public class SizeFileFilterTest extends BaseFilterTest {
private static FileObject zipFileObj;
+ @AfterClass
+ public static void afterClass() throws IOException {
+
+ minFileInfo = null;
+ minFile = null;
+
+ optFileInfo = null;
+ optFile = null;
+
+ maxFileInfo = null;
+ maxFile = null;
+
+ zipFileObj.close();
+ FileUtils.deleteQuietly(zipFile);
+ zipFile = null;
+
+ FileUtils.deleteDirectory(testDir);
+ testDir = null;
+ }
+
@BeforeClass
public static void beforeClass() throws IOException {
testDir = getTestDir(SizeFileFilterTest.class.getName());
@@ -79,26 +99,6 @@ public class SizeFileFilterTest extends BaseFilterTest {
}
- @AfterClass
- public static void afterClass() throws IOException {
-
- minFileInfo = null;
- minFile = null;
-
- optFileInfo = null;
- optFile = null;
-
- maxFileInfo = null;
- maxFile = null;
-
- zipFileObj.close();
- FileUtils.deleteQuietly(zipFile);
- zipFile = null;
-
- FileUtils.deleteDirectory(testDir);
- testDir = null;
- }
-
@Test
public void testSizeFileFilterLong() throws FileSystemException {
@@ -127,38 +127,6 @@ public class SizeFileFilterTest extends BaseFilterTest {
}
@Test
- public void testSizeRangeFileFilter() throws FileSystemException {
-
- SizeRangeFileFilter testee;
-
- testee = new SizeRangeFileFilter(2, 6);
- Assert.assertTrue(testee.accept(minFileInfo));
- Assert.assertTrue(testee.accept(optFileInfo));
- Assert.assertTrue(testee.accept(maxFileInfo));
-
- testee = new SizeRangeFileFilter(3, 6);
- Assert.assertFalse(testee.accept(minFileInfo));
- Assert.assertTrue(testee.accept(optFileInfo));
- Assert.assertTrue(testee.accept(maxFileInfo));
-
- testee = new SizeRangeFileFilter(2, 5);
- Assert.assertTrue(testee.accept(minFileInfo));
- Assert.assertTrue(testee.accept(optFileInfo));
- Assert.assertFalse(testee.accept(maxFileInfo));
-
- testee = new SizeRangeFileFilter(3, 5);
- Assert.assertFalse(testee.accept(minFileInfo));
- Assert.assertTrue(testee.accept(optFileInfo));
- Assert.assertFalse(testee.accept(maxFileInfo));
-
- testee = new SizeRangeFileFilter(4, 4);
- Assert.assertFalse(testee.accept(minFileInfo));
- Assert.assertTrue(testee.accept(optFileInfo));
- Assert.assertFalse(testee.accept(maxFileInfo));
-
- }
-
- @Test
public void testSizeFileFilterZipDir() throws FileSystemException {
// Same test with ZIP file
@@ -194,5 +162,37 @@ public class SizeFileFilterTest extends BaseFilterTest {
}
+ @Test
+ public void testSizeRangeFileFilter() throws FileSystemException {
+
+ SizeRangeFileFilter testee;
+
+ testee = new SizeRangeFileFilter(2, 6);
+ Assert.assertTrue(testee.accept(minFileInfo));
+ Assert.assertTrue(testee.accept(optFileInfo));
+ Assert.assertTrue(testee.accept(maxFileInfo));
+
+ testee = new SizeRangeFileFilter(3, 6);
+ Assert.assertFalse(testee.accept(minFileInfo));
+ Assert.assertTrue(testee.accept(optFileInfo));
+ Assert.assertTrue(testee.accept(maxFileInfo));
+
+ testee = new SizeRangeFileFilter(2, 5);
+ Assert.assertTrue(testee.accept(minFileInfo));
+ Assert.assertTrue(testee.accept(optFileInfo));
+ Assert.assertFalse(testee.accept(maxFileInfo));
+
+ testee = new SizeRangeFileFilter(3, 5);
+ Assert.assertFalse(testee.accept(minFileInfo));
+ Assert.assertTrue(testee.accept(optFileInfo));
+ Assert.assertFalse(testee.accept(maxFileInfo));
+
+ testee = new SizeRangeFileFilter(4, 4);
+ Assert.assertFalse(testee.accept(minFileInfo));
+ Assert.assertTrue(testee.accept(optFileInfo));
+ Assert.assertFalse(testee.accept(maxFileInfo));
+
+ }
+
}
// CHECKSTYLE:ON
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/SymbolicLinkFileFilterTest.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/SymbolicLinkFileFilterTest.java
index e23d51d..c8b2b87 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/SymbolicLinkFileFilterTest.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/filter/SymbolicLinkFileFilterTest.java
@@ -69,6 +69,27 @@ public class SymbolicLinkFileFilterTest extends BaseFilterTest {
private static FileObject zipFileObject;
+ @AfterClass
+ public static void afterClass() throws IOException {
+ targetFile = null;
+ targetFileInfo = null;
+ linkFile = null;
+ linkFileInfo = null;
+ notExistingFile = null;
+ notExistingFileInfo = null;
+ if (zipFileObject != null) {
+ zipFileObject.close();
+ }
+ if (zipFile != null) {
+ FileUtils.deleteQuietly(zipFile);
+ zipFile = null;
+ }
+ if (testDir != null) {
+ FileUtils.deleteDirectory(testDir);
+ testDir = null;
+ }
+ }
+
@BeforeClass
public static void beforeClass() throws IOException {
Assume.assumeTrue(Boolean.getBoolean(SymbolicLinkFileFilterTest.class.getSimpleName() + ".Enable"));
@@ -94,27 +115,6 @@ public class SymbolicLinkFileFilterTest extends BaseFilterTest {
zipFileObject = getZipFileObject(zipFile);
}
- @AfterClass
- public static void afterClass() throws IOException {
- targetFile = null;
- targetFileInfo = null;
- linkFile = null;
- linkFileInfo = null;
- notExistingFile = null;
- notExistingFileInfo = null;
- if (zipFileObject != null) {
- zipFileObject.close();
- }
- if (zipFile != null) {
- FileUtils.deleteQuietly(zipFile);
- zipFile = null;
- }
- if (testDir != null) {
- FileUtils.deleteDirectory(testDir);
- testDir = null;
- }
- }
-
@Test
public void testAcceptActual() throws FileSystemException {
final FileFilter testee = SymbolicLinkFileFilter.ACTUAL;
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/impl/DefaultFileMonitorTest.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/impl/DefaultFileMonitorTest.java
index 2328e52..69d8c3f 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/impl/DefaultFileMonitorTest.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/impl/DefaultFileMonitorTest.java
@@ -40,16 +40,18 @@ import org.junit.Ignore;
import org.junit.Test;
/**
- * Test to verify DefaultFileMonitor
+ * Tests {@link DefaultFileMonitor}.
*/
public class DefaultFileMonitorTest {
private static class CountingListener implements FileListener {
private final AtomicLong created = new AtomicLong();
+ private final AtomicLong changed = new AtomicLong();
+ private final AtomicLong deleted = new AtomicLong();
@Override
public void fileChanged(final FileChangeEvent event) {
- throw new UnsupportedOperationException();
+ changed.incrementAndGet();
}
@Override
@@ -59,7 +61,7 @@ public class DefaultFileMonitorTest {
@Override
public void fileDeleted(final FileChangeEvent event) {
- throw new UnsupportedOperationException();
+ deleted.incrementAndGet();
}
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/impl/DefaultFileSystemManagerTest.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/impl/DefaultFileSystemManagerTest.java
index 29d0aea..7667fe7 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/impl/DefaultFileSystemManagerTest.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/impl/DefaultFileSystemManagerTest.java
@@ -83,6 +83,11 @@ public class DefaultFileSystemManagerTest {
}
}
+ @Test
+ public void testCreateBz2FileSystem() throws FileSystemException {
+ testCreateFileSystem("src/test/resources/test-data/bla.txt.bz2", Bzip2FileObject.class);
+ }
+
private void testCreateFileSystem(final String path, Class<?> clazz) throws FileSystemException {
FileSystemManager manager = VFS.getManager();
try (FileObject localFileObject = manager.resolveFile(new File(path).getAbsolutePath());
@@ -98,11 +103,6 @@ public class DefaultFileSystemManagerTest {
}
@Test
- public void testCreateBz2FileSystem() throws FileSystemException {
- testCreateFileSystem("src/test/resources/test-data/bla.txt.bz2", Bzip2FileObject.class);
- }
-
- @Test
public void testCreateJarFileSystem() throws FileSystemException {
testCreateFileSystem("src/test/resources/test-data/nested.jar", JarFileObject.class);
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/impl/VfsClassLoaderTests.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/impl/VfsClassLoaderTests.java
index 5498b71..75323eb 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/impl/VfsClassLoaderTests.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/impl/VfsClassLoaderTests.java
@@ -38,11 +38,26 @@ import org.junit.Test;
public class VfsClassLoaderTests extends AbstractProviderTestCase {
/**
- * Returns the capabilities required by the tests of this test case.
+ * Non-Delegating Class Loader.
*/
- @Override
- protected Capability[] getRequiredCapabilities() {
- return new Capability[] { Capability.READ_CONTENT, Capability.URI };
+ public static class MockClassloader extends ClassLoader {
+ MockClassloader() {
+ super(null);
+ }
+
+ @Override
+ protected Class<?> findClass(final String name) throws ClassNotFoundException {
+ fail("Not intended to be used for class loading.");
+ return null;
+ }
+
+ /**
+ * This method will not return any hit to VFSClassLoader#testGetResourcesJARs.
+ */
+ @Override
+ public Enumeration<URL> getResources(final String name) throws IOException {
+ return Collections.enumeration(Collections.<URL>emptyList());
+ }
}
/**
@@ -53,45 +68,11 @@ public class VfsClassLoaderTests extends AbstractProviderTestCase {
}
/**
- * Tests loading a class.
- */
- @Test
- public void testLoadClass() throws Exception {
- final VFSClassLoader loader = createClassLoader();
-
- final Class<?> testClass = loader.loadClass("code.ClassToLoad");
- final Package pack = testClass.getPackage();
- assertEquals("code", pack.getName());
- verifyPackage(pack, false);
-
- final Object testObject = testClass.newInstance();
- assertEquals("**PRIVATE**", testObject.toString());
- }
-
- /**
- * Tests loading a resource.
- */
- @Test
- public void testLoadResource() throws Exception {
- final VFSClassLoader loader = createClassLoader();
-
- final URL resource = loader.getResource("read-tests/file1.txt");
-
- assertNotNull(resource);
- final URLConnection urlCon = resource.openConnection();
- assertSameURLContent(FILE1_CONTENT, urlCon);
- }
-
- /**
- * Tests package sealing.
+ * Returns the capabilities required by the tests of this test case.
*/
- @Test
- public void testSealing() throws Exception {
- final VFSClassLoader loader = createClassLoader();
- final Class<?> testClass = loader.loadClass("code.sealed.AnotherClass");
- final Package pack = testClass.getPackage();
- assertEquals("code.sealed", pack.getName());
- verifyPackage(pack, true);
+ @Override
+ protected Capability[] getRequiredCapabilities() {
+ return new Capability[] { Capability.READ_CONTENT, Capability.URI };
}
/**
@@ -181,6 +162,48 @@ public class VfsClassLoaderTests extends AbstractProviderTestCase {
}
/**
+ * Tests loading a class.
+ */
+ @Test
+ public void testLoadClass() throws Exception {
+ final VFSClassLoader loader = createClassLoader();
+
+ final Class<?> testClass = loader.loadClass("code.ClassToLoad");
+ final Package pack = testClass.getPackage();
+ assertEquals("code", pack.getName());
+ verifyPackage(pack, false);
+
+ final Object testObject = testClass.newInstance();
+ assertEquals("**PRIVATE**", testObject.toString());
+ }
+
+ /**
+ * Tests loading a resource.
+ */
+ @Test
+ public void testLoadResource() throws Exception {
+ final VFSClassLoader loader = createClassLoader();
+
+ final URL resource = loader.getResource("read-tests/file1.txt");
+
+ assertNotNull(resource);
+ final URLConnection urlCon = resource.openConnection();
+ assertSameURLContent(FILE1_CONTENT, urlCon);
+ }
+
+ /**
+ * Tests package sealing.
+ */
+ @Test
+ public void testSealing() throws Exception {
+ final VFSClassLoader loader = createClassLoader();
+ final Class<?> testClass = loader.loadClass("code.sealed.AnotherClass");
+ final Package pack = testClass.getPackage();
+ assertEquals("code.sealed", pack.getName());
+ verifyPackage(pack, true);
+ }
+
+ /**
* Verify the package loaded with class loader.
*/
private void verifyPackage(final Package pack, final boolean sealed) {
@@ -202,27 +225,4 @@ public class VfsClassLoaderTests extends AbstractProviderTestCase {
assertFalse(pack.isSealed());
}
}
-
- /**
- * Non-Delegating Class Loader.
- */
- public static class MockClassloader extends ClassLoader {
- MockClassloader() {
- super(null);
- }
-
- /**
- * This method will not return any hit to VFSClassLoader#testGetResourcesJARs.
- */
- @Override
- public Enumeration<URL> getResources(final String name) throws IOException {
- return Collections.enumeration(Collections.<URL>emptyList());
- }
-
- @Override
- protected Class<?> findClass(final String name) throws ClassNotFoundException {
- fail("Not intended to be used for class loading.");
- return null;
- }
- }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/operations/BasicOperationsTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/operations/BasicOperationsTestCase.java
index 342e222..9a273ea 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/operations/BasicOperationsTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/operations/BasicOperationsTestCase.java
@@ -44,25 +44,25 @@ public class BasicOperationsTestCase {
/** This FileOperationsProvider is a VfsComponent and records invocations. */
static class MyFileOperationProviderComp extends MyFileOprationProviderBase implements VfsComponent {
@Override
- public void setLogger(final Log logger) {
- assertNotNull("setLogger", logger);
- ops |= 1;
+ public void close() {
+ ops |= 8;
}
@Override
- public void setContext(final VfsComponentContext context) {
- assertNotNull("setContext", context);
- ops |= 2;
+ public void init() throws FileSystemException {
+ ops |= 4;
}
@Override
- public void init() throws FileSystemException {
- ops |= 4;
+ public void setContext(final VfsComponentContext context) {
+ assertNotNull("setContext", context);
+ ops |= 2;
}
@Override
- public void close() {
- ops |= 8;
+ public void setLogger(final Log logger) {
+ assertNotNull("setLogger", logger);
+ ops |= 1;
}
}
@@ -111,6 +111,19 @@ public class BasicOperationsTestCase {
}
/**
+ * JUnit Fixture: Tear Down the FSM.
+ *
+ * @throws FileSystemException for runtime problems
+ */
+ @After
+ public void tearDown() throws FileSystemException {
+ if (manager != null) {
+ manager.close();
+ manager = null;
+ }
+ }
+
+ /**
* Ensure FileOperationProviders which are VfsComponents are set up and teared down.
*
* @throws FileSystemException for runtime problems
@@ -183,17 +196,4 @@ public class BasicOperationsTestCase {
}
assertSame(32, myop.ops); // getOperation was called
}
-
- /**
- * JUnit Fixture: Tear Down the FSM.
- *
- * @throws FileSystemException for runtime problems
- */
- @After
- public void tearDown() throws FileSystemException {
- if (manager != null) {
- manager.close();
- manager = null;
- }
- }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/perf/FileNamePerformance.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/perf/FileNamePerformance.java
index 2960975..4093fa9 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/perf/FileNamePerformance.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/perf/FileNamePerformance.java
@@ -38,36 +38,36 @@ public class FileNamePerformance {
testFiles(mgr);
}
- private static void testFiles(final FileSystemManager mgr) throws FileSystemException {
+ private static void testChildren(final FileObject root) throws FileSystemException {
for (int i = 0; i < 10; i++) {
// warmup jvm
- mgr.resolveFile(
- "smb://HOME\\vfsusr:vfs%2f%25\\te:st@10.0.1.54/vfsusr/many/path/elements/with%25esc/any%25where/to/file.txt");
+ root.resolveFile("/many/path/elements/with%25esc/any%25where/to/file.txt");
}
final long startMillis = System.currentTimeMillis();
for (int i = 0; i < NUOF_RESOLVES; i++) {
- mgr.resolveFile(
- "smb://HOME\\vfsusr:vfs%2f%25\\te:st@10.0.1.54/vfsusr/many/path/elements/with%25esc/any%25where/to/file.txt");
+ root.resolveFile("/many/path/elements/with%25esc/any%25where/to/file.txt");
}
final long endMillis = System.currentTimeMillis();
- System.err.println("time to resolve " + NUOF_RESOLVES + " files: " + (endMillis - startMillis) + " milliseconds");
+ System.err.println("time to resolve " + NUOF_RESOLVES + " children: " + (endMillis - startMillis) + " milliseconds");
}
- private static void testChildren(final FileObject root) throws FileSystemException {
+ private static void testFiles(final FileSystemManager mgr) throws FileSystemException {
for (int i = 0; i < 10; i++) {
// warmup jvm
- root.resolveFile("/many/path/elements/with%25esc/any%25where/to/file.txt");
+ mgr.resolveFile(
+ "smb://HOME\\vfsusr:vfs%2f%25\\te:st@10.0.1.54/vfsusr/many/path/elements/with%25esc/any%25where/to/file.txt");
}
final long startMillis = System.currentTimeMillis();
for (int i = 0; i < NUOF_RESOLVES; i++) {
- root.resolveFile("/many/path/elements/with%25esc/any%25where/to/file.txt");
+ mgr.resolveFile(
+ "smb://HOME\\vfsusr:vfs%2f%25\\te:st@10.0.1.54/vfsusr/many/path/elements/with%25esc/any%25where/to/file.txt");
}
final long endMillis = System.currentTimeMillis();
- System.err.println("time to resolve " + NUOF_RESOLVES + " children: " + (endMillis - startMillis) + " milliseconds");
+ System.err.println("time to resolve " + NUOF_RESOLVES + " files: " + (endMillis - startMillis) + " milliseconds");
}
private static void testNames(final FileSystemManager mgr, final FileName rootName) throws FileSystemException {
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/AbstractFileNameTest.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/AbstractFileNameTest.java
index cfbe24d..9e4a4bc 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/AbstractFileNameTest.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/AbstractFileNameTest.java
@@ -26,16 +26,16 @@ public class AbstractFileNameTest {
public void testHashSignEncoded() {
final AbstractFileName fileName = new AbstractFileName("file", "/foo/bar/file#name.txt", FileType.FILE) {
@Override
- public FileName createName(final String absolutePath, final FileType fileType) {
- return null;
- }
-
- @Override
protected void appendRootUri(final StringBuilder buffer, final boolean addPassword) {
if (addPassword) {
buffer.append("pass");
}
}
+
+ @Override
+ public FileName createName(final String absolutePath, final FileType fileType) {
+ return null;
+ }
};
Assert.assertEquals("pass/foo/bar/file%23name.txt", fileName.getURI());
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/UriParserTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/UriParserTestCase.java
index 47551a4..6344188 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/UriParserTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/UriParserTestCase.java
@@ -34,6 +34,11 @@ public class UriParserTestCase {
}
@Test
+ public void testColonInFileName() {
+ Assert.assertNull(UriParser.extractScheme("some/path/some:file"));
+ }
+
+ @Test
public void testColonInFileNameAndNotSupportedScheme() {
Assert.assertNull(UriParser.extractScheme(schemes, "some:file"));
}
@@ -44,18 +49,13 @@ public class UriParserTestCase {
}
@Test
- public void testNormalScheme() {
- Assert.assertEquals("ftp", UriParser.extractScheme(schemes, "ftp://user:pass@host/some/path/some:file"));
- }
-
- @Test
- public void testOneSlashScheme() {
- Assert.assertEquals("file", UriParser.extractScheme(schemes, "file:/user:pass@host/some/path/some:file"));
+ public void testColonNotFollowedBySlash() {
+ Assert.assertEquals("file", UriParser.extractScheme(schemes, "file:user/subdir/some/path/some:file"));
}
@Test
- public void testColonNotFollowedBySlash() {
- Assert.assertEquals("file", UriParser.extractScheme(schemes, "file:user/subdir/some/path/some:file"));
+ public void testNormalScheme() {
+ Assert.assertEquals("ftp", UriParser.extractScheme(schemes, "ftp://user:pass@host/some/path/some:file"));
}
@Test
@@ -66,15 +66,15 @@ public class UriParserTestCase {
}
@Test
+ public void testOneSlashScheme() {
+ Assert.assertEquals("file", UriParser.extractScheme(schemes, "file:/user:pass@host/some/path/some:file"));
+ }
+
+ @Test
public void testOneSlashSchemeWithBuffer() {
final StringBuilder buffer = new StringBuilder();
UriParser.extractScheme(schemes, "file:/user:pass@host/some/path/some:file", buffer);
Assert.assertEquals("/user:pass@host/some/path/some:file", buffer.toString());
}
- @Test
- public void testColonInFileName() {
- Assert.assertNull(UriParser.extractScheme("some/path/some:file"));
- }
-
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/ftps/AbstractFtpsProviderTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/ftps/AbstractFtpsProviderTestCase.java
index d7ce462..4608387 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/ftps/AbstractFtpsProviderTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/ftps/AbstractFtpsProviderTestCase.java
@@ -42,6 +42,36 @@ import org.junit.Assert;
* Abstract tests for FTP file systems.
*/
abstract class AbstractFtpsProviderTestCase extends AbstractProviderTestConfig {
+ static final class FtpProviderTestSuite extends ProviderTestSuite {
+ private final boolean implicit;
+
+ public FtpProviderTestSuite(final AbstractFtpsProviderTestCase providerConfig) throws Exception {
+ super(providerConfig);
+ this.implicit = providerConfig.isImplicit();
+ }
+
+ @Override
+ protected void setUp() throws Exception {
+ if (getSystemTestUriOverride() == null) {
+ setUpClass(implicit);
+ }
+ super.setUp();
+ }
+
+ @Override
+ protected void tearDown() throws Exception {
+ try {
+ // This will report running threads of the FTP server.
+ // However, shutting down the FTP server first will always
+ // report an exception closing the manager, because the
+ // server is already down
+ super.tearDown();
+ } finally {
+ tearDownClass();
+ }
+ }
+ }
+
private static int SocketPort;
/**
@@ -51,8 +81,6 @@ abstract class AbstractFtpsProviderTestCase extends AbstractProviderTestConfig {
private static FtpServer Server;
- protected FileSystemOptions fileSystemOptions;
-
private static final String TEST_URI = "test.ftps.uri";
private static final String USER_PROPS_RES = "org.apache.ftpsserver/users.properties";
@@ -130,37 +158,7 @@ abstract class AbstractFtpsProviderTestCase extends AbstractProviderTestConfig {
}
}
- static final class FtpProviderTestSuite extends ProviderTestSuite {
- private final boolean implicit;
-
- public FtpProviderTestSuite(final AbstractFtpsProviderTestCase providerConfig) throws Exception {
- super(providerConfig);
- this.implicit = providerConfig.isImplicit();
- }
-
- @Override
- protected void setUp() throws Exception {
- if (getSystemTestUriOverride() == null) {
- setUpClass(implicit);
- }
- super.setUp();
- }
-
- @Override
- protected void tearDown() throws Exception {
- try {
- // This will report running threads of the FTP server.
- // However, shutting down the FTP server first will always
- // report an exception closing the manager, because the
- // server is already down
- super.tearDown();
- } finally {
- tearDownClass();
- }
- }
- }
-
- protected abstract boolean isImplicit();
+ protected FileSystemOptions fileSystemOptions;
/**
* Returns the base folder for tests. You can override the DEFAULT_URI by using the system property name defined by
@@ -183,10 +181,7 @@ abstract class AbstractFtpsProviderTestCase extends AbstractProviderTestConfig {
return fileSystemOptions;
}
- protected void setupOptions(final FtpsFileSystemConfigBuilder builder) {
- builder.setConnectTimeout(fileSystemOptions, Duration.ofSeconds(1));
- builder.setDataTimeout(fileSystemOptions, Duration.ofSeconds(2));
- }
+ protected abstract boolean isImplicit();
/**
* Prepares the file system manager.
@@ -195,4 +190,9 @@ abstract class AbstractFtpsProviderTestCase extends AbstractProviderTestConfig {
public void prepare(final DefaultFileSystemManager manager) throws Exception {
manager.addProvider("ftps", new FtpsFileProvider());
}
+
+ protected void setupOptions(final FtpsFileSystemConfigBuilder builder) {
+ builder.setConnectTimeout(fileSystemOptions, Duration.ofSeconds(1));
+ builder.setDataTimeout(fileSystemOptions, Duration.ofSeconds(2));
+ }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/ftps/FtpsProviderExplicitTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/ftps/FtpsProviderExplicitTestCase.java
index 8a7d849..d9a58ff 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/ftps/FtpsProviderExplicitTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/ftps/FtpsProviderExplicitTestCase.java
@@ -23,6 +23,13 @@ import junit.framework.Test;
*/
public class FtpsProviderExplicitTestCase extends AbstractFtpsProviderTestCase {
+ /**
+ * Creates the test suite for the ftps file system.
+ */
+ public static Test suite() throws Exception {
+ return new FtpProviderTestSuite(new FtpsProviderExplicitTestCase());
+ }
+
@Override
protected boolean isImplicit() {
return false;
@@ -34,11 +41,4 @@ public class FtpsProviderExplicitTestCase extends AbstractFtpsProviderTestCase {
builder.setDataChannelProtectionLevel(fileSystemOptions, FtpsDataChannelProtectionLevel.P);
builder.setFtpsMode(fileSystemOptions, FtpsMode.EXPLICIT);
}
-
- /**
- * Creates the test suite for the ftps file system.
- */
- public static Test suite() throws Exception {
- return new FtpProviderTestSuite(new FtpsProviderExplicitTestCase());
- }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/ftps/FtpsProviderImplicitTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/ftps/FtpsProviderImplicitTestCase.java
index 25233ce..83605d5 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/ftps/FtpsProviderImplicitTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/ftps/FtpsProviderImplicitTestCase.java
@@ -27,6 +27,13 @@ import junit.framework.Test;
* @see <a href="http://en.wikipedia.org/wiki/FTPS#Implicit">Wikipedia: FTPS/Implicit</a>
*/
public class FtpsProviderImplicitTestCase extends AbstractFtpsProviderTestCase {
+ /**
+ * Creates the test suite for the ftps file system.
+ */
+ public static Test suite() throws Exception {
+ return new FtpProviderTestSuite(new FtpsProviderImplicitTestCase());
+ }
+
@Override
protected boolean isImplicit() {
return true;
@@ -37,11 +44,4 @@ public class FtpsProviderImplicitTestCase extends AbstractFtpsProviderTestCase {
super.setupOptions(builder);
builder.setFtpsMode(fileSystemOptions, FtpsMode.IMPLICIT);
}
-
- /**
- * Creates the test suite for the ftps file system.
- */
- public static Test suite() throws Exception {
- return new FtpProviderTestSuite(new FtpsProviderImplicitTestCase());
- }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/hdfs/HdfsFileProviderTest.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/hdfs/HdfsFileProviderTest.java
index 1bd22c1..6097459 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/hdfs/HdfsFileProviderTest.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/hdfs/HdfsFileProviderTest.java
@@ -68,34 +68,6 @@ public class HdfsFileProviderTest {
protected static Configuration conf;
protected static MiniDFSCluster cluster;
- @BeforeClass
- public static void setUp() throws Exception {
- Logger.getRootLogger().setLevel(Level.ERROR);
-
- // Put the MiniDFSCluster directory in the target directory
- final File data = new File("target/test/hdfstestdata").getAbsoluteFile();
- data.mkdirs();
- System.setProperty("test.build.data", data.toString());
- FileUtils.cleanDirectory(data);
-
- // Setup HDFS
- conf = new Configuration();
- conf.set(FileSystem.FS_DEFAULT_NAME_KEY, HDFS_URI);
- conf.set("hadoop.security.token.service.use_ip", "true");
- conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, 1024 * 1024); // 1M blocksize
-
- setUmask(conf);
-
- cluster = new MiniDFSCluster(PORT, conf, 1, true, true, true, null, null, null, null);
- cluster.waitActive();
-
- // Set up the VFS
- manager = new DefaultFileSystemManager();
- manager.addProvider("hdfs", new HdfsFileProvider());
- manager.init();
- hdfs = cluster.getFileSystem();
- }
-
/**
* Add {@code dfs.datanode.data.dir.perm} setting if OS needs it.
* <P>
@@ -125,6 +97,34 @@ public class HdfsFileProviderTest {
}
}
+ @BeforeClass
+ public static void setUp() throws Exception {
+ Logger.getRootLogger().setLevel(Level.ERROR);
+
+ // Put the MiniDFSCluster directory in the target directory
+ final File data = new File("target/test/hdfstestdata").getAbsoluteFile();
+ data.mkdirs();
+ System.setProperty("test.build.data", data.toString());
+ FileUtils.cleanDirectory(data);
+
+ // Setup HDFS
+ conf = new Configuration();
+ conf.set(FileSystem.FS_DEFAULT_NAME_KEY, HDFS_URI);
+ conf.set("hadoop.security.token.service.use_ip", "true");
+ conf.setLong(DFSConfigKeys.DFS_BLOCK_SIZE_KEY, 1024 * 1024); // 1M blocksize
+
+ setUmask(conf);
+
+ cluster = new MiniDFSCluster(PORT, conf, 1, true, true, true, null, null, null, null);
+ cluster.waitActive();
+
+ // Set up the VFS
+ manager = new DefaultFileSystemManager();
+ manager.addProvider("hdfs", new HdfsFileProvider());
+ manager.init();
+ hdfs = cluster.getFileSystem();
+ }
+
@AfterClass
public static void tearDown() throws Exception {
if (null != hdfs) {
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/jar/NestedJarTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/jar/NestedJarTestCase.java
index 27e013f..9bc7d31 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/jar/NestedJarTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/jar/NestedJarTestCase.java
@@ -39,15 +39,6 @@ public class NestedJarTestCase extends AbstractProviderTestConfig {
}
/**
- * Prepares the file system manager.
- */
- @Override
- public void prepare(final DefaultFileSystemManager manager) throws Exception {
- manager.addProvider("jar", new JarFileProvider());
- manager.addExtensionMap("jar", "jar");
- }
-
- /**
* Returns the base folder for tests.
*/
@Override
@@ -61,4 +52,13 @@ public class NestedJarTestCase extends AbstractProviderTestConfig {
final FileObject nestedFS = manager.createFileSystem(jarFile);
return nestedFS.resolveFile("/");
}
+
+ /**
+ * Prepares the file system manager.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager) throws Exception {
+ manager.addProvider("jar", new JarFileProvider());
+ manager.addExtensionMap("jar", "jar");
+ }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/local/ConversionTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/local/ConversionTestCase.java
index 7fed56c..8e974b8 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/local/ConversionTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/local/ConversionTestCase.java
@@ -40,19 +40,6 @@ public class ConversionTestCase {
@Test
@Ignore
- public void testFileNameWithSpaces() throws URISyntaxException, IOException {
- final File file = new File("target", "a name.txt");
- final String fileURL = file.toURI().toURL().toExternalForm();
- assertEquals(file.getAbsoluteFile(), new File(file.toURI().getPath()));
- assertEquals(file.getAbsoluteFile(), new File(new URL(fileURL).toURI().getPath()));
-
- final FileSystemManager manager = VFS.getManager();
- final FileObject fo = manager.resolveFile(fileURL);
- assertEquals(file.getAbsoluteFile(), new File(new URL(fo.getURL().toExternalForm()).toURI().getPath()));
- }
-
- @Test
- @Ignore
public void testFileNameWithCharacters() throws URISyntaxException, IOException {
final File file = new File("target", "+# %&.txt");
final String fileURL = file.toURI().toURL().toExternalForm();
@@ -71,4 +58,17 @@ public class ConversionTestCase {
}
}
+ @Test
+ @Ignore
+ public void testFileNameWithSpaces() throws URISyntaxException, IOException {
+ final File file = new File("target", "a name.txt");
+ final String fileURL = file.toURI().toURL().toExternalForm();
+ assertEquals(file.getAbsoluteFile(), new File(file.toURI().getPath()));
+ assertEquals(file.getAbsoluteFile(), new File(new URL(fileURL).toURI().getPath()));
+
+ final FileSystemManager manager = VFS.getManager();
+ final FileObject fo = manager.resolveFile(fileURL);
+ assertEquals(file.getAbsoluteFile(), new File(new URL(fo.getURL().toExternalForm()).toURI().getPath()));
+ }
+
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/local/WindowsFileNameTests.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/local/WindowsFileNameTests.java
index a932719..e938e7a 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/local/WindowsFileNameTests.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/local/WindowsFileNameTests.java
@@ -32,6 +32,37 @@ import org.junit.Test;
public class WindowsFileNameTests extends AbstractProviderTestCase {
@Test
+ public void testWindowsFilenameParserError() throws Exception {
+ // check VFS-338 with 2+4 slashes we want a dedicated error
+ try {
+ final String FILE = "file://////";
+ final DefaultFileSystemManager manager = getManager();
+ Assert.assertNotNull("Unexpected null manager for test " + this, manager);
+ final FileObject fo = manager.resolveFile(FILE);
+ fail("Windows File Parser should not allow " + FILE + " " + fo);
+ } catch (FileSystemException ex) {
+ assertEquals("Exception code", "vfs.provider/invalid-absolute-uri.error", ex.getCode());
+ ex = (FileSystemException) ex.getCause();
+ assertEquals("Exception code", "vfs.provider.local/not-absolute-file-name.error", ex.getCode());
+ }
+ }
+
+ @Test
+ public void testWindowsFilenameUNCStartError() throws Exception {
+ try {
+ final String FILE = "file://///";
+ final DefaultFileSystemManager manager = getManager();
+ Assert.assertNotNull("Unexpected null manager for test " + this, manager);
+ final FileObject fo = manager.resolveFile(FILE);
+ fail("Windows File Parser should not allow " + FILE + " " + fo);
+ } catch (FileSystemException ex) {
+ assertEquals("Exception code", "vfs.provider/invalid-absolute-uri.error", ex.getCode());
+ ex = (FileSystemException) ex.getCause();
+ assertEquals("Exception code", "vfs.provider.local/missing-share-name.error", ex.getCode());
+ }
+ }
+
+ @Test
public void testWindowsRoots() throws Exception {
// valid URI forms of the filesystem root
final String[] tests = new String[] { "file:///C:/", "file://C:/", "file:/C:/", "file:C:/" };
@@ -74,35 +105,4 @@ public class WindowsFileNameTests extends AbstractProviderTestCase {
}
}
}
-
- @Test
- public void testWindowsFilenameUNCStartError() throws Exception {
- try {
- final String FILE = "file://///";
- final DefaultFileSystemManager manager = getManager();
- Assert.assertNotNull("Unexpected null manager for test " + this, manager);
- final FileObject fo = manager.resolveFile(FILE);
- fail("Windows File Parser should not allow " + FILE + " " + fo);
- } catch (FileSystemException ex) {
- assertEquals("Exception code", "vfs.provider/invalid-absolute-uri.error", ex.getCode());
- ex = (FileSystemException) ex.getCause();
- assertEquals("Exception code", "vfs.provider.local/missing-share-name.error", ex.getCode());
- }
- }
-
- @Test
- public void testWindowsFilenameParserError() throws Exception {
- // check VFS-338 with 2+4 slashes we want a dedicated error
- try {
- final String FILE = "file://////";
- final DefaultFileSystemManager manager = getManager();
- Assert.assertNotNull("Unexpected null manager for test " + this, manager);
- final FileObject fo = manager.resolveFile(FILE);
- fail("Windows File Parser should not allow " + FILE + " " + fo);
- } catch (FileSystemException ex) {
- assertEquals("Exception code", "vfs.provider/invalid-absolute-uri.error", ex.getCode());
- ex = (FileSystemException) ex.getCause();
- assertEquals("Exception code", "vfs.provider.local/not-absolute-file-name.error", ex.getCode());
- }
- }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/ram/CustomRamProviderTest.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/ram/CustomRamProviderTest.java
index d330905..b089873 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/ram/CustomRamProviderTest.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/ram/CustomRamProviderTest.java
@@ -49,11 +49,11 @@ import org.junit.Test;
* Custom tests for RamProvider.
*/
public class CustomRamProviderTest {
+ private static final byte[] NON_EMPTY_FILE_CONTENT = new byte[] { 1, 2, 3 };
+
/** List of URL special characters encoded for AbstractFileObject#getChild */
final char[] ENC = { /*'#',*/ '!', '?'};
- private static final byte[] NON_EMPTY_FILE_CONTENT = new byte[] { 1, 2, 3 };
-
private final List<Closeable> closeables = new ArrayList<>();
FileSystemOptions defaultRamFso = new FileSystemOptions();
@@ -134,6 +134,41 @@ public class CustomRamProviderTest {
}
@Test
+ public void testFSOptions() throws Exception {
+ // Default FS
+ final FileObject fo1 = manager.resolveFile("ram:/");
+ final FileObject fo2 = manager.resolveFile("ram:/");
+ assertSame("Both files should exist in the same fs instance.", fo1.getFileSystem(), fo2.getFileSystem());
+
+ FileSystemOptions fsOptions = fo1.getFileSystem().getFileSystemOptions();
+ long maxFilesystemSize = RamFileSystemConfigBuilder.getInstance().getLongMaxSize(fsOptions);
+ assertEquals("Filesystem option maxSize must be unlimited", Long.MAX_VALUE, maxFilesystemSize);
+
+ // Small FS
+ final FileObject fo3 = manager.resolveFile("ram:/fo3", smallSizedFso);
+ final FileObject fo4 = manager.resolveFile("ram:/", smallSizedFso);
+ assertSame("Both files should exist in the same FileSystem instance.", fo3.getFileSystem(), fo4.getFileSystem());
+ assertNotSame("Both files should exist in different FileSystem instance.", fo1.getFileSystem(), fo3.getFileSystem());
+
+ fsOptions = fo3.getFileSystem().getFileSystemOptions();
+ maxFilesystemSize = RamFileSystemConfigBuilder.getInstance().getLongMaxSize(fsOptions);
+ assertEquals("Filesystem option maxSize must be set", 10, maxFilesystemSize);
+ }
+
+ /**
+ * Tests VFS-625.
+ * @throws FileSystemException
+ */
+ @Test
+ public void testMoveFile() throws FileSystemException {
+ final FileObject fileSource = manager.resolveFile("ram://virtual/source");
+ fileSource.createFile();
+ final FileObject fileDest = manager.resolveFile("ram://virtual/dest");
+ Assert.assertTrue(fileSource.canRenameTo(fileDest));
+ fileSource.moveTo(fileDest);
+ }
+
+ @Test
public void testReadEmptyFileByteByByte() throws FileSystemException, IOException {
final InputStream input = this.createEmptyFile();
assertEquals("Empty file didnt return EOF -1", -1, input.read());
@@ -223,26 +258,57 @@ public class CustomRamProviderTest {
}
+ /**
+ * Test if listing files with known scheme prefix works.
+ * <p>
+ * This test is not RamProvider specific but it uses it as a simple test-bed.
+ * Verifies VFS-741.
+ */
@Test
- public void testFSOptions() throws Exception {
- // Default FS
- final FileObject fo1 = manager.resolveFile("ram:/");
- final FileObject fo2 = manager.resolveFile("ram:/");
- assertSame("Both files should exist in the same fs instance.", fo1.getFileSystem(), fo2.getFileSystem());
+ public void testSchemePrefix() throws FileSystemException
+ {
+ // use a :-prefix with a known scheme (unknown scheme works since VFS-398)
+ final String KNOWN_SCHEME = manager.getSchemes()[0]; // typically "ram"
- FileSystemOptions fsOptions = fo1.getFileSystem().getFileSystemOptions();
- long maxFilesystemSize = RamFileSystemConfigBuilder.getInstance().getLongMaxSize(fsOptions);
- assertEquals("Filesystem option maxSize must be unlimited", Long.MAX_VALUE, maxFilesystemSize);
+ // we test with this file name
+ final String testDir = "/prefixtest/";
+ final String testFileName = KNOWN_SCHEME + ":test:txt";
+ final String expectedName = testDir + testFileName;
- // Small FS
- final FileObject fo3 = manager.resolveFile("ram:/fo3", smallSizedFso);
- final FileObject fo4 = manager.resolveFile("ram:/", smallSizedFso);
- assertSame("Both files should exist in the same FileSystem instance.", fo3.getFileSystem(), fo4.getFileSystem());
- assertNotSame("Both files should exist in different FileSystem instance.", fo1.getFileSystem(), fo3.getFileSystem());
+ final FileObject dir = prepareSpecialFile(testDir, testFileName);
- fsOptions = fo3.getFileSystem().getFileSystemOptions();
- maxFilesystemSize = RamFileSystemConfigBuilder.getInstance().getLongMaxSize(fsOptions);
- assertEquals("Filesystem option maxSize must be set", 10, maxFilesystemSize);
+
+ // verify we can list dir
+
+ // if not it throws:
+ // Caused by: org.apache.commons.vfs2.FileSystemException: Invalid descendent file name "ram:data:test.txt".
+ // at org.apache.commons.vfs2.impl.DefaultFileSystemManager.resolveName
+ // at org.apache.commons.vfs2.provider.AbstractFileObject.getChildren
+ // at org.apache.commons.vfs2.provider.AbstractFileObject.traverse
+ // at org.apache.commons.vfs2.provider.AbstractFileObject.findFiles
+
+ // test methods to get the child:
+ final FileObject[] findFilesResult = dir.findFiles(new AllFileSelector()); // includes dir
+ final FileObject[] getChildrenResult = dir.getChildren();
+ final FileObject getChildResult = dir.getChild(testFileName);
+
+ // validate findFiles returns expected result
+ assertEquals("Unexpected result findFiles: " + Arrays.toString(findFilesResult), 2, findFilesResult.length);
+ String resultName = findFilesResult[0].getName().getPathDecoded();
+ assertEquals("findFiles Child name does not match", expectedName, resultName);
+ assertEquals("Did findFiles but child was no file", FileType.FILE, findFilesResult[0].getType());
+
+ // validate getChildren returns expected result
+ assertEquals("Unexpected result getChildren: " + Arrays.toString(getChildrenResult), 1, getChildrenResult.length);
+ resultName = getChildrenResult[0].getName().getPathDecoded();
+ assertEquals("getChildren Child name does not match", expectedName, resultName);
+ assertEquals("Did getChildren but child was no file", FileType.FILE, getChildrenResult[0].getType());
+
+ // validate getChild returns expected child
+ assertNotNull("Did not find direct child", getChildResult);
+ resultName = getChildResult.getName().getPathDecoded();
+ assertEquals("getChild name does not match", expectedName, resultName);
+ assertEquals("getChild was no file", FileType.FILE, getChildResult.getType());
}
@Test
@@ -268,18 +334,6 @@ public class CustomRamProviderTest {
}
}
- /**
- * Tests VFS-625.
- * @throws FileSystemException
- */
- @Test
- public void testMoveFile() throws FileSystemException {
- final FileObject fileSource = manager.resolveFile("ram://virtual/source");
- fileSource.createFile();
- final FileObject fileDest = manager.resolveFile("ram://virtual/dest");
- Assert.assertTrue(fileSource.canRenameTo(fileDest));
- fileSource.moveTo(fileDest);
- }
/**
* Test some special file name symbols.
@@ -323,58 +377,4 @@ public class CustomRamProviderTest {
assertEquals("getChild name does not match", expectedName, resultName);
assertEquals("getChild was no file", FileType.FILE, getChildResult.getType());
}
-
-
- /**
- * Test if listing files with known scheme prefix works.
- * <p>
- * This test is not RamProvider specific but it uses it as a simple test-bed.
- * Verifies VFS-741.
- */
- @Test
- public void testSchemePrefix() throws FileSystemException
- {
- // use a :-prefix with a known scheme (unknown scheme works since VFS-398)
- final String KNOWN_SCHEME = manager.getSchemes()[0]; // typically "ram"
-
- // we test with this file name
- final String testDir = "/prefixtest/";
- final String testFileName = KNOWN_SCHEME + ":test:txt";
- final String expectedName = testDir + testFileName;
-
- final FileObject dir = prepareSpecialFile(testDir, testFileName);
-
-
- // verify we can list dir
-
- // if not it throws:
- // Caused by: org.apache.commons.vfs2.FileSystemException: Invalid descendent file name "ram:data:test.txt".
- // at org.apache.commons.vfs2.impl.DefaultFileSystemManager.resolveName
- // at org.apache.commons.vfs2.provider.AbstractFileObject.getChildren
- // at org.apache.commons.vfs2.provider.AbstractFileObject.traverse
- // at org.apache.commons.vfs2.provider.AbstractFileObject.findFiles
-
- // test methods to get the child:
- final FileObject[] findFilesResult = dir.findFiles(new AllFileSelector()); // includes dir
- final FileObject[] getChildrenResult = dir.getChildren();
- final FileObject getChildResult = dir.getChild(testFileName);
-
- // validate findFiles returns expected result
- assertEquals("Unexpected result findFiles: " + Arrays.toString(findFilesResult), 2, findFilesResult.length);
- String resultName = findFilesResult[0].getName().getPathDecoded();
- assertEquals("findFiles Child name does not match", expectedName, resultName);
- assertEquals("Did findFiles but child was no file", FileType.FILE, findFilesResult[0].getType());
-
- // validate getChildren returns expected result
- assertEquals("Unexpected result getChildren: " + Arrays.toString(getChildrenResult), 1, getChildrenResult.length);
- resultName = getChildrenResult[0].getName().getPathDecoded();
- assertEquals("getChildren Child name does not match", expectedName, resultName);
- assertEquals("Did getChildren but child was no file", FileType.FILE, getChildrenResult[0].getType());
-
- // validate getChild returns expected child
- assertNotNull("Did not find direct child", getChildResult);
- resultName = getChildResult.getName().getPathDecoded();
- assertEquals("getChild name does not match", expectedName, resultName);
- assertEquals("getChild was no file", FileType.FILE, getChildResult.getType());
- }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/ram/RamProviderTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/ram/RamProviderTestCase.java
index c46762a..12cd28c 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/ram/RamProviderTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/ram/RamProviderTestCase.java
@@ -31,8 +31,6 @@ import junit.framework.Test;
* Tests for the RAM file system.
*/
public class RamProviderTestCase extends AbstractProviderTestConfig {
- private boolean inited;
-
/** logger */
private static final Log log = LogFactory.getLog(RamProviderTestCase.class);
@@ -43,23 +41,7 @@ public class RamProviderTestCase extends AbstractProviderTestConfig {
return new ProviderTestSuite(new RamProviderTestCase());
}
- /**
- * Prepares the file system manager.
- *
- * Imports test data from the disk.
- *
- * @throws Exception
- */
- @Override
- public void prepare(final DefaultFileSystemManager manager) throws Exception {
- try {
- manager.addProvider("ram", new RamFileProvider());
- manager.addProvider("file", new DefaultLocalFileProvider());
- } catch (final Exception e) {
- log.error(e);
- throw e;
- }
- }
+ private boolean inited;
/**
* Returns the base folder for tests.
@@ -79,4 +61,22 @@ public class RamProviderTestCase extends AbstractProviderTestConfig {
final String uri = "ram:/";
return manager.resolveFile(uri);
}
+
+ /**
+ * Prepares the file system manager.
+ *
+ * Imports test data from the disk.
+ *
+ * @throws Exception
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager) throws Exception {
+ try {
+ manager.addProvider("ram", new RamFileProvider());
+ manager.addProvider("file", new DefaultLocalFileProvider());
+ } catch (final Exception e) {
+ log.error(e);
+ throw e;
+ }
+ }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/res/ResSchemeTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/res/ResSchemeTestCase.java
index 97d3f93..ba63469 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/res/ResSchemeTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/res/ResSchemeTestCase.java
@@ -47,6 +47,12 @@ public class ResSchemeTestCase {
Assert.assertTrue(VFS.getManager().resolveFile("res://test.properties").exists());
}
+ @Test(expected = FileSystemException.class)
+ public void test_resolveFile_String_SSSnull() throws FileSystemException {
+ // Resulting path is empty
+ Assert.assertTrue(VFS.getManager().resolveFile("res:///").exists());
+ }
+
@Test
public void test_resolveFile_URI() throws FileSystemException, URISyntaxException {
Assert.assertTrue(VFS.getManager().resolveFile(new URI("res:test.properties")).exists());
@@ -92,10 +98,4 @@ public class ResSchemeTestCase {
// Resulting path is empty
Assert.assertTrue(VFS.getManager().resolveURI("res:///").isFile());
}
-
- @Test(expected = FileSystemException.class)
- public void test_resolveFile_String_SSSnull() throws FileSystemException {
- // Resulting path is empty
- Assert.assertTrue(VFS.getManager().resolveFile("res:///").exists());
- }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/res/ResourceProviderTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/res/ResourceProviderTestCase.java
index e415166..15e27b8 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/res/ResourceProviderTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/res/ResourceProviderTestCase.java
@@ -37,21 +37,21 @@ public class ResourceProviderTestCase extends AbstractProviderTestConfig {
}
/**
- * Prepares the file system manager. This implementation does nothing.
+ * Returns the base folder for tests.
*/
@Override
- public void prepare(final DefaultFileSystemManager manager) throws Exception {
- manager.addProvider("res", new ResourceFileProvider());
- manager.addProvider("file", new UrlFileProvider());
- manager.addProvider("jar", new JarFileProvider());
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
+ final String baseDir = AbstractVfsTestCase.getResourceTestDirectory();
+ return manager.resolveFile("res:" + baseDir);
}
/**
- * Returns the base folder for tests.
+ * Prepares the file system manager. This implementation does nothing.
*/
@Override
- public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
- final String baseDir = AbstractVfsTestCase.getResourceTestDirectory();
- return manager.resolveFile("res:" + baseDir);
+ public void prepare(final DefaultFileSystemManager manager) throws Exception {
+ manager.addProvider("res", new ResourceFileProvider());
+ manager.addProvider("file", new UrlFileProvider());
+ manager.addProvider("jar", new JarFileProvider());
}
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/res/Vfs444TestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/res/Vfs444TestCase.java
index 7f69131..2838a43 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/res/Vfs444TestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/res/Vfs444TestCase.java
@@ -35,66 +35,42 @@ import org.junit.Test;
*/
public class Vfs444TestCase extends AbstractProviderTestConfig {
- public static junit.framework.Test suite() throws Exception {
- final ProviderTestSuite suite = new ProviderTestSuite(new Vfs444TestCase(), true);
- suite.addTests(Vfs444Tests.class);
- return suite;
- }
-
- /**
- * Prepares the file system manager. This implementation does nothing.
- */
- @Override
- public void prepare(final DefaultFileSystemManager manager) throws Exception {
- manager.addProvider("res", new ResourceFileProvider());
- manager.addProvider("zip", new ZipFileProvider());
- }
-
- /**
- * Returns the base folder for tests.
- */
- @Override
- public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
- final String baseDir = AbstractVfsTestCase.getResourceTestDirectory();
- return manager.resolveFile("zip:res:" + baseDir + "/test.zip");
- }
-
public static class Vfs444Tests extends AbstractProviderTestCase {
@Test
- public void testResolveFullPathURI0() throws FileSystemException {
- final FileName result = getManager().resolveURI("res:test-data/test.zip");
- Assert.assertTrue(result.isFile());
- }
-
- @Test
public void testResolveFullPathFile0() throws FileSystemException {
final FileObject result = getManager().resolveFile("res:test-data/test.zip");
Assert.assertTrue(result.exists());
}
@Test
- public void testResolveFullPathURI1() throws FileSystemException {
- final FileName result = getManager().resolveURI("res:/test-data/test.zip");
- Assert.assertTrue(result.isFile());
+ public void testResolveFullPathFile1() throws FileSystemException {
+ final FileObject result = getManager().resolveFile("res:/test-data/test.zip");
+ Assert.assertTrue(result.exists());
}
@Test
- public void testResolveFullPathFile1() throws FileSystemException {
- final FileObject result = getManager().resolveFile("res:/test-data/test.zip");
+ public void testResolveFullPathFile2() throws FileSystemException {
+ final FileObject result = getManager().resolveFile("res://test-data/test.zip");
Assert.assertTrue(result.exists());
}
@Test
- public void testResolveFullPathURI2() throws FileSystemException {
- final FileName result = getManager().resolveURI("res://test-data/test.zip");
+ public void testResolveFullPathURI0() throws FileSystemException {
+ final FileName result = getManager().resolveURI("res:test-data/test.zip");
Assert.assertTrue(result.isFile());
}
@Test
- public void testResolveFullPathFile2() throws FileSystemException {
- final FileObject result = getManager().resolveFile("res://test-data/test.zip");
- Assert.assertTrue(result.exists());
+ public void testResolveFullPathURI1() throws FileSystemException {
+ final FileName result = getManager().resolveURI("res:/test-data/test.zip");
+ Assert.assertTrue(result.isFile());
+ }
+
+ @Test
+ public void testResolveFullPathURI2() throws FileSystemException {
+ final FileName result = getManager().resolveURI("res://test-data/test.zip");
+ Assert.assertTrue(result.isFile());
}
@Test
@@ -113,4 +89,28 @@ public class Vfs444TestCase extends AbstractProviderTestConfig {
Assert.assertTrue(result.exists());
}
}
+
+ public static junit.framework.Test suite() throws Exception {
+ final ProviderTestSuite suite = new ProviderTestSuite(new Vfs444TestCase(), true);
+ suite.addTests(Vfs444Tests.class);
+ return suite;
+ }
+
+ /**
+ * Returns the base folder for tests.
+ */
+ @Override
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
+ final String baseDir = AbstractVfsTestCase.getResourceTestDirectory();
+ return manager.resolveFile("zip:res:" + baseDir + "/test.zip");
+ }
+
+ /**
+ * Prepares the file system manager. This implementation does nothing.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager) throws Exception {
+ manager.addProvider("res", new ResourceFileProvider());
+ manager.addProvider("zip", new ZipFileProvider());
+ }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/sftp/AbstractSftpProviderTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/sftp/AbstractSftpProviderTestCase.java
index c87e3e7..49a8007 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/sftp/AbstractSftpProviderTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/sftp/AbstractSftpProviderTestCase.java
@@ -73,176 +73,149 @@ import com.jcraft.jsch.TestIdentityRepositoryFactory;
*/
abstract class AbstractSftpProviderTestCase extends AbstractProviderTestConfig {
- /**
- * The underlying file system
- */
- protected SftpFileSystem fileSystem;
+ private static class MySftpSubsystem extends SftpSubsystem {
+ TreeMap<String, Integer> permissions = new TreeMap<>();
+ private int _version;
- /**
- * Implements FileSystemFactory because SSHd does not know about users and home directories.
- */
- static final class TestFileSystemFactory implements FileSystemFactory {
- /**
- * Accepts only the known test user.
- */
@Override
- public FileSystemView createFileSystemView(final Session session) throws IOException {
- final String userName = session.getUsername();
- if (!DEFAULT_USER.equals(userName)) {
- return null;
- }
- return new TestFileSystemView(AbstractVfsTestCase.getTestDirectory(), userName);
- }
- }
+ protected void process(final Buffer buffer) throws IOException {
+ final int rpos = buffer.rpos();
+ final int length = buffer.getInt();
+ final int type = buffer.getByte();
+ final int id = buffer.getInt();
- /**
- * Implements FileSystemView because SSHd does not know about users and home directories.
- */
- static final class TestFileSystemView implements FileSystemView {
- private final String homeDirStr;
+ switch (type) {
+ case SSH_FXP_SETSTAT:
+ case SSH_FXP_FSETSTAT: {
+ // Get the path
+ final String path = buffer.getString();
+ // Get the permission
+ final SftpAttrs attrs = new SftpAttrs(buffer);
+ permissions.put(path, attrs.permissions);
+ // System.err.format("Setting [%s] permission to %o%n", path, attrs.permissions);
+ break;
+ }
- private final String userName;
+ case SSH_FXP_REMOVE: {
+ // Remove cached attributes
+ final String path = buffer.getString();
+ permissions.remove(path);
+ // System.err.format("Removing [%s] permission cache%n", path);
+ break;
+ }
- // private boolean caseInsensitive;
+ case SSH_FXP_INIT: {
+ // Just grab the version here
+ this._version = id;
+ break;
+ }
+ }
- public TestFileSystemView(final String homeDirStr, final String userName) {
- this.homeDirStr = new File(homeDirStr).getAbsolutePath();
- this.userName = userName;
- }
+ buffer.rpos(rpos);
+ super.process(buffer);
- @Override
- public SshFile getFile(final SshFile baseDir, final String file) {
- return this.getFile(baseDir.getAbsolutePath(), file);
}
@Override
- public SshFile getFile(final String file) {
- return this.getFile(homeDirStr, file);
- }
-
- protected SshFile getFile(final String dir, final String file) {
- final String home = removePrefix(NativeSshFile.normalizeSeparateChar(homeDirStr));
- String userFileName = removePrefix(NativeSshFile.normalizeSeparateChar(file));
- final File sshFile = userFileName.startsWith(home) ? new File(userFileName) : new File(home, userFileName);
- userFileName = removePrefix(NativeSshFile.normalizeSeparateChar(sshFile.getAbsolutePath()));
- return new TestNativeSshFile(userFileName, sshFile, userName);
- }
-
- private String removePrefix(final String s) {
- final int index = s.indexOf('/');
- if (index < 1) {
- return s;
+ protected void writeAttrs(final Buffer buffer, final SshFile file, final int flags) throws IOException {
+ if (!file.doesExist()) {
+ throw new FileNotFoundException(file.getAbsolutePath());
}
- return s.substring(index);
- }
- }
-
- /**
- * Extends NativeSshFile because its constructor is protected and I do not want to create a whole NativeSshFile
- * implementation for testing.
- */
- static class TestNativeSshFile extends NativeSshFile {
- TestNativeSshFile(final String fileName, final File file, final String userName) {
- super(fileName, file, userName);
- }
- }
- private static int SocketPort;
-
- private static final String DEFAULT_USER = "testtest";
-
- // private static final String DEFAULT_PWD = "testtest";
+ int p = 0;
- protected static String ConnectionUri;
+ final Integer cached = permissions.get(file.getAbsolutePath());
+ if (cached != null) {
+ // Use cached permissions
+ // System.err.format("Using cached [%s] permission of %o%n", file.getAbsolutePath(), cached);
+ p |= cached;
+ } else {
+ // Use permissions from Java file
+ if (file.isReadable()) {
+ p |= S_IRUSR;
+ }
+ if (file.isWritable()) {
+ p |= S_IWUSR;
+ }
+ if (file.isExecutable()) {
+ p |= S_IXUSR;
+ }
+ }
- private static SshServer Server;
+ if (_version >= 4) {
+ final long size = file.getSize();
+ // String username = session.getUsername();
+ final long lastModif = file.getLastModified();
+ if (file.isFile()) {
+ buffer.putInt(SSH_FILEXFER_ATTR_PERMISSIONS);
+ buffer.putByte((byte) SSH_FILEXFER_TYPE_REGULAR);
+ buffer.putInt(p);
+ } else if (file.isDirectory()) {
+ buffer.putInt(SSH_FILEXFER_ATTR_PERMISSIONS);
+ buffer.putByte((byte) SSH_FILEXFER_TYPE_DIRECTORY);
+ buffer.putInt(p);
+ } else {
+ buffer.putInt(0);
+ buffer.putByte((byte) SSH_FILEXFER_TYPE_UNKNOWN);
+ }
+ } else {
+ if (file.isFile()) {
+ p |= 0100000;
+ }
+ if (file.isDirectory()) {
+ p |= 0040000;
+ }
- private static final String TEST_URI = "test.sftp.uri";
+ if (file.isFile()) {
+ buffer.putInt(SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_PERMISSIONS | SSH_FILEXFER_ATTR_ACMODTIME);
+ buffer.putLong(file.getSize());
+ buffer.putInt(p);
+ buffer.putInt(file.getLastModified() / 1000);
+ buffer.putInt(file.getLastModified() / 1000);
+ } else if (file.isDirectory()) {
+ buffer.putInt(SSH_FILEXFER_ATTR_PERMISSIONS | SSH_FILEXFER_ATTR_ACMODTIME);
+ buffer.putInt(p);
+ buffer.putInt(file.getLastModified() / 1000);
+ buffer.putInt(file.getLastModified() / 1000);
+ } else {
+ buffer.putInt(0);
+ }
+ }
+ }
- /**
- * True if we are testing the SFTP stream proxy
- */
- protected static String getSystemTestUriOverride() {
- return System.getProperty(TEST_URI);
}
- /**
- * Creates and starts an embedded Apache SSHd Server (MINA).
- *
- * @throws FtpException
- * @throws IOException
- */
- private static void setUpClass(final boolean isExecChannelClosed) throws IOException {
- if (Server != null) {
- return;
- }
- // System.setProperty("vfs.sftp.sshdir", getTestDirectory() + "/../vfs.sftp.sshdir");
- final String tmpDir = System.getProperty("java.io.tmpdir");
- Server = SshServer.setUpDefaultServer();
- Server.setPort(0);
- if (SecurityUtils.isBouncyCastleRegistered()) {
- // A temporary file will hold the key
- final File keyFile = File.createTempFile("key", ".pem", new File(tmpDir));
- keyFile.deleteOnExit();
- // It has to be deleted in order to be generated
- keyFile.delete();
+ private static class SftpAttrs {
+ int flags;
+ private int uid;
+ long size;
+ private int gid;
+ private int atime;
+ private int permissions;
+ private int mtime;
+ private String[] extended;
- final PEMGeneratorHostKeyProvider keyProvider = new PEMGeneratorHostKeyProvider(keyFile.getAbsolutePath());
- Server.setKeyPairProvider(keyProvider);
- } else {
- Server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(tmpDir + "/key.ser"));
- }
- final List<NamedFactory<Command>> list = new ArrayList<>(1);
- list.add(new NamedFactory<Command>() {
+ private SftpAttrs(final Buffer buf) {
+ final int flags = buf.getInt();
- @Override
- public String getName() {
- return "sftp";
+ if ((flags & SftpATTRS.SSH_FILEXFER_ATTR_SIZE) != 0) {
+ size = buf.getLong();
}
-
- @Override
- public Command create() {
- return new MySftpSubsystem();
+ if ((flags & SftpATTRS.SSH_FILEXFER_ATTR_UIDGID) != 0) {
+ uid = buf.getInt();
+ gid = buf.getInt();
}
- });
- Server.setSubsystemFactories(list);
- Server.setPasswordAuthenticator((username, password, session) -> StringUtils.equals(username, password));
- Server.setPublickeyAuthenticator((username, key, session) -> true);
- Server.setForwardingFilter(new ForwardingFilter() {
- @Override
- public boolean canConnect(final InetSocketAddress address, final ServerSession session) {
- return true;
+ if ((flags & SftpATTRS.SSH_FILEXFER_ATTR_PERMISSIONS) != 0) {
+ permissions = buf.getInt();
}
-
- @Override
- public boolean canForwardAgent(final ServerSession session) {
- return true;
+ if ((flags & SftpATTRS.SSH_FILEXFER_ATTR_ACMODTIME) != 0) {
+ atime = buf.getInt();
}
-
- @Override
- public boolean canForwardX11(final ServerSession session) {
- return true;
+ if ((flags & SftpATTRS.SSH_FILEXFER_ATTR_ACMODTIME) != 0) {
+ mtime = buf.getInt();
}
- @Override
- public boolean canListen(final InetSocketAddress address, final ServerSession session) {
- return true;
- }
- });
- // Allows the execution of commands
- Server.setCommandFactory(new ScpCommandFactory(new TestCommandFactory(isExecChannelClosed)));
- // HACK Start
- // How do we really do simple user to directory matching?
- Server.setFileSystemFactory(new TestFileSystemFactory());
- // HACK End
- Server.start();
- SocketPort = Server.getPort();
- ConnectionUri = String.format("sftp://%s@localhost:%d", DEFAULT_USER, SocketPort);
- // HACK Start
- // How do we really do simple security?
- // Do this after we start the server to simplify this set up code.
- Server.getUserAuthFactories().add(new UserAuthNone.Factory());
- // HACK End
+ }
}
static class SftpProviderTestSuite extends ProviderTestSuite {
@@ -275,51 +248,6 @@ abstract class AbstractSftpProviderTestCase extends AbstractProviderTestConfig {
}
- protected abstract boolean isExecChannelClosed();
-
- /**
- * Stops the embedded Apache SSHd Server (MINA).
- *
- * @throws InterruptedException
- */
- private static void tearDownClass() throws InterruptedException {
- if (Server != null) {
- Server.stop();
- Server = null;
- }
- }
-
- /**
- * Returns the base folder for tests.
- */
- @Override
- public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
- String uri = getSystemTestUriOverride();
- if (uri == null) {
- uri = ConnectionUri;
- }
-
- final FileSystemOptions fileSystemOptions = new FileSystemOptions();
- final SftpFileSystemConfigBuilder builder = SftpFileSystemConfigBuilder.getInstance();
- builder.setStrictHostKeyChecking(fileSystemOptions, "no");
- builder.setUserInfo(fileSystemOptions, new TrustEveryoneUserInfo());
- builder.setIdentityRepositoryFactory(fileSystemOptions, new TestIdentityRepositoryFactory());
- builder.setConnectTimeout(fileSystemOptions, Duration.ofSeconds(60));
- builder.setSessionTimeout(fileSystemOptions, Duration.ofSeconds(60));
-
- final FileObject fileObject = manager.resolveFile(uri, fileSystemOptions);
- this.fileSystem = (SftpFileSystem) fileObject.getFileSystem();
- return fileObject;
- }
-
- /**
- * Prepares the file system manager.
- */
- @Override
- public void prepare(final DefaultFileSystemManager manager) throws Exception {
- manager.addProvider("sftp", new SftpFileProvider());
- }
-
/**
* The command factory for the SSH server: Handles these commands
* <p>
@@ -346,13 +274,8 @@ abstract class AbstractSftpProviderTestCase extends AbstractProviderTestConfig {
public InputStream in;
@Override
- public void setInputStream(final InputStream in) {
- this.in = in;
- }
-
- @Override
- public void setOutputStream(final OutputStream out) {
- this.out = out;
+ public void destroy() {
+ // empty
}
@Override
@@ -367,6 +290,16 @@ abstract class AbstractSftpProviderTestCase extends AbstractProviderTestConfig {
}
@Override
+ public void setInputStream(final InputStream in) {
+ this.in = in;
+ }
+
+ @Override
+ public void setOutputStream(final OutputStream out) {
+ this.out = out;
+ }
+
+ @Override
public void start(final Environment env) throws IOException {
int code = 0;
if (command.equals("id -G") || command.equals("id -u")) {
@@ -406,16 +339,92 @@ abstract class AbstractSftpProviderTestCase extends AbstractProviderTestConfig {
}
callback.onExit(code);
}
-
- @Override
- public void destroy() {
- // empty
- }
};
}
}
/**
+ * Implements FileSystemFactory because SSHd does not know about users and home directories.
+ */
+ static final class TestFileSystemFactory implements FileSystemFactory {
+ /**
+ * Accepts only the known test user.
+ */
+ @Override
+ public FileSystemView createFileSystemView(final Session session) throws IOException {
+ final String userName = session.getUsername();
+ if (!DEFAULT_USER.equals(userName)) {
+ return null;
+ }
+ return new TestFileSystemView(AbstractVfsTestCase.getTestDirectory(), userName);
+ }
+ }
+
+ /**
+ * Implements FileSystemView because SSHd does not know about users and home directories.
+ */
+ static final class TestFileSystemView implements FileSystemView {
+ private final String homeDirStr;
+
+ private final String userName;
+
+ // private boolean caseInsensitive;
+
+ public TestFileSystemView(final String homeDirStr, final String userName) {
+ this.homeDirStr = new File(homeDirStr).getAbsolutePath();
+ this.userName = userName;
+ }
+
+ @Override
+ public SshFile getFile(final SshFile baseDir, final String file) {
+ return this.getFile(baseDir.getAbsolutePath(), file);
+ }
+
+ @Override
+ public SshFile getFile(final String file) {
+ return this.getFile(homeDirStr, file);
+ }
+
+ protected SshFile getFile(final String dir, final String file) {
+ final String home = removePrefix(NativeSshFile.normalizeSeparateChar(homeDirStr));
+ String userFileName = removePrefix(NativeSshFile.normalizeSeparateChar(file));
+ final File sshFile = userFileName.startsWith(home) ? new File(userFileName) : new File(home, userFileName);
+ userFileName = removePrefix(NativeSshFile.normalizeSeparateChar(sshFile.getAbsolutePath()));
+ return new TestNativeSshFile(userFileName, sshFile, userName);
+ }
+
+ private String removePrefix(final String s) {
+ final int index = s.indexOf('/');
+ if (index < 1) {
+ return s;
+ }
+ return s.substring(index);
+ }
+ }
+
+ // private static final String DEFAULT_PWD = "testtest";
+
+ /**
+ * Extends NativeSshFile because its constructor is protected and I do not want to create a whole NativeSshFile
+ * implementation for testing.
+ */
+ static class TestNativeSshFile extends NativeSshFile {
+ TestNativeSshFile(final String fileName, final File file, final String userName) {
+ super(fileName, file, userName);
+ }
+ }
+
+ private static int SocketPort;
+
+ private static final String DEFAULT_USER = "testtest";
+
+ protected static String ConnectionUri;
+
+ private static SshServer Server;
+
+ private static final String TEST_URI = "test.sftp.uri";
+
+ /**
* Creates a pipe thread that connects an input to an output
*
* @param name The name of the thread (for debugging purposes)
@@ -451,148 +460,139 @@ abstract class AbstractSftpProviderTestCase extends AbstractProviderTestConfig {
thread.start();
}
- private static class SftpAttrs {
- int flags;
- private int uid;
- long size;
- private int gid;
- private int atime;
- private int permissions;
- private int mtime;
- private String[] extended;
-
- private SftpAttrs(final Buffer buf) {
- final int flags = buf.getInt();
-
- if ((flags & SftpATTRS.SSH_FILEXFER_ATTR_SIZE) != 0) {
- size = buf.getLong();
- }
- if ((flags & SftpATTRS.SSH_FILEXFER_ATTR_UIDGID) != 0) {
- uid = buf.getInt();
- gid = buf.getInt();
- }
- if ((flags & SftpATTRS.SSH_FILEXFER_ATTR_PERMISSIONS) != 0) {
- permissions = buf.getInt();
- }
- if ((flags & SftpATTRS.SSH_FILEXFER_ATTR_ACMODTIME) != 0) {
- atime = buf.getInt();
- }
- if ((flags & SftpATTRS.SSH_FILEXFER_ATTR_ACMODTIME) != 0) {
- mtime = buf.getInt();
- }
+ /**
+ * True if we are testing the SFTP stream proxy
+ */
+ protected static String getSystemTestUriOverride() {
+ return System.getProperty(TEST_URI);
+ }
+ /**
+ * Creates and starts an embedded Apache SSHd Server (MINA).
+ *
+ * @throws FtpException
+ * @throws IOException
+ */
+ private static void setUpClass(final boolean isExecChannelClosed) throws IOException {
+ if (Server != null) {
+ return;
}
- }
+ // System.setProperty("vfs.sftp.sshdir", getTestDirectory() + "/../vfs.sftp.sshdir");
+ final String tmpDir = System.getProperty("java.io.tmpdir");
+ Server = SshServer.setUpDefaultServer();
+ Server.setPort(0);
+ if (SecurityUtils.isBouncyCastleRegistered()) {
+ // A temporary file will hold the key
+ final File keyFile = File.createTempFile("key", ".pem", new File(tmpDir));
+ keyFile.deleteOnExit();
+ // It has to be deleted in order to be generated
+ keyFile.delete();
- private static class MySftpSubsystem extends SftpSubsystem {
- TreeMap<String, Integer> permissions = new TreeMap<>();
- private int _version;
+ final PEMGeneratorHostKeyProvider keyProvider = new PEMGeneratorHostKeyProvider(keyFile.getAbsolutePath());
+ Server.setKeyPairProvider(keyProvider);
+ } else {
+ Server.setKeyPairProvider(new SimpleGeneratorHostKeyProvider(tmpDir + "/key.ser"));
+ }
+ final List<NamedFactory<Command>> list = new ArrayList<>(1);
+ list.add(new NamedFactory<Command>() {
- @Override
- protected void process(final Buffer buffer) throws IOException {
- final int rpos = buffer.rpos();
- final int length = buffer.getInt();
- final int type = buffer.getByte();
- final int id = buffer.getInt();
+ @Override
+ public Command create() {
+ return new MySftpSubsystem();
+ }
- switch (type) {
- case SSH_FXP_SETSTAT:
- case SSH_FXP_FSETSTAT: {
- // Get the path
- final String path = buffer.getString();
- // Get the permission
- final SftpAttrs attrs = new SftpAttrs(buffer);
- permissions.put(path, attrs.permissions);
- // System.err.format("Setting [%s] permission to %o%n", path, attrs.permissions);
- break;
- }
+ @Override
+ public String getName() {
+ return "sftp";
+ }
+ });
+ Server.setSubsystemFactories(list);
+ Server.setPasswordAuthenticator((username, password, session) -> StringUtils.equals(username, password));
+ Server.setPublickeyAuthenticator((username, key, session) -> true);
+ Server.setForwardingFilter(new ForwardingFilter() {
+ @Override
+ public boolean canConnect(final InetSocketAddress address, final ServerSession session) {
+ return true;
+ }
- case SSH_FXP_REMOVE: {
- // Remove cached attributes
- final String path = buffer.getString();
- permissions.remove(path);
- // System.err.format("Removing [%s] permission cache%n", path);
- break;
- }
+ @Override
+ public boolean canForwardAgent(final ServerSession session) {
+ return true;
+ }
- case SSH_FXP_INIT: {
- // Just grab the version here
- this._version = id;
- break;
- }
+ @Override
+ public boolean canForwardX11(final ServerSession session) {
+ return true;
}
- buffer.rpos(rpos);
- super.process(buffer);
+ @Override
+ public boolean canListen(final InetSocketAddress address, final ServerSession session) {
+ return true;
+ }
+ });
+ // Allows the execution of commands
+ Server.setCommandFactory(new ScpCommandFactory(new TestCommandFactory(isExecChannelClosed)));
+ // HACK Start
+ // How do we really do simple user to directory matching?
+ Server.setFileSystemFactory(new TestFileSystemFactory());
+ // HACK End
+ Server.start();
+ SocketPort = Server.getPort();
+ ConnectionUri = String.format("sftp://%s@localhost:%d", DEFAULT_USER, SocketPort);
+ // HACK Start
+ // How do we really do simple security?
+ // Do this after we start the server to simplify this set up code.
+ Server.getUserAuthFactories().add(new UserAuthNone.Factory());
+ // HACK End
+ }
+ /**
+ * Stops the embedded Apache SSHd Server (MINA).
+ *
+ * @throws InterruptedException
+ */
+ private static void tearDownClass() throws InterruptedException {
+ if (Server != null) {
+ Server.stop();
+ Server = null;
}
+ }
- @Override
- protected void writeAttrs(final Buffer buffer, final SshFile file, final int flags) throws IOException {
- if (!file.doesExist()) {
- throw new FileNotFoundException(file.getAbsolutePath());
- }
+ /**
+ * The underlying file system
+ */
+ protected SftpFileSystem fileSystem;
- int p = 0;
+ /**
+ * Returns the base folder for tests.
+ */
+ @Override
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
+ String uri = getSystemTestUriOverride();
+ if (uri == null) {
+ uri = ConnectionUri;
+ }
- final Integer cached = permissions.get(file.getAbsolutePath());
- if (cached != null) {
- // Use cached permissions
- // System.err.format("Using cached [%s] permission of %o%n", file.getAbsolutePath(), cached);
- p |= cached;
- } else {
- // Use permissions from Java file
- if (file.isReadable()) {
- p |= S_IRUSR;
- }
- if (file.isWritable()) {
- p |= S_IWUSR;
- }
- if (file.isExecutable()) {
- p |= S_IXUSR;
- }
- }
+ final FileSystemOptions fileSystemOptions = new FileSystemOptions();
+ final SftpFileSystemConfigBuilder builder = SftpFileSystemConfigBuilder.getInstance();
+ builder.setStrictHostKeyChecking(fileSystemOptions, "no");
+ builder.setUserInfo(fileSystemOptions, new TrustEveryoneUserInfo());
+ builder.setIdentityRepositoryFactory(fileSystemOptions, new TestIdentityRepositoryFactory());
+ builder.setConnectTimeout(fileSystemOptions, Duration.ofSeconds(60));
+ builder.setSessionTimeout(fileSystemOptions, Duration.ofSeconds(60));
- if (_version >= 4) {
- final long size = file.getSize();
- // String username = session.getUsername();
- final long lastModif = file.getLastModified();
- if (file.isFile()) {
- buffer.putInt(SSH_FILEXFER_ATTR_PERMISSIONS);
- buffer.putByte((byte) SSH_FILEXFER_TYPE_REGULAR);
- buffer.putInt(p);
- } else if (file.isDirectory()) {
- buffer.putInt(SSH_FILEXFER_ATTR_PERMISSIONS);
- buffer.putByte((byte) SSH_FILEXFER_TYPE_DIRECTORY);
- buffer.putInt(p);
- } else {
- buffer.putInt(0);
- buffer.putByte((byte) SSH_FILEXFER_TYPE_UNKNOWN);
- }
- } else {
- if (file.isFile()) {
- p |= 0100000;
- }
- if (file.isDirectory()) {
- p |= 0040000;
- }
+ final FileObject fileObject = manager.resolveFile(uri, fileSystemOptions);
+ this.fileSystem = (SftpFileSystem) fileObject.getFileSystem();
+ return fileObject;
+ }
- if (file.isFile()) {
- buffer.putInt(SSH_FILEXFER_ATTR_SIZE | SSH_FILEXFER_ATTR_PERMISSIONS | SSH_FILEXFER_ATTR_ACMODTIME);
- buffer.putLong(file.getSize());
- buffer.putInt(p);
- buffer.putInt(file.getLastModified() / 1000);
- buffer.putInt(file.getLastModified() / 1000);
- } else if (file.isDirectory()) {
- buffer.putInt(SSH_FILEXFER_ATTR_PERMISSIONS | SSH_FILEXFER_ATTR_ACMODTIME);
- buffer.putInt(p);
- buffer.putInt(file.getLastModified() / 1000);
- buffer.putInt(file.getLastModified() / 1000);
- } else {
- buffer.putInt(0);
- }
- }
- }
+ protected abstract boolean isExecChannelClosed();
+ /**
+ * Prepares the file system manager.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager) throws Exception {
+ manager.addProvider("sftp", new SftpFileProvider());
}
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/sftp/SftpProviderClosedExecChannelTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/sftp/SftpProviderClosedExecChannelTestCase.java
index a0da54b..15366a0 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/sftp/SftpProviderClosedExecChannelTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/sftp/SftpProviderClosedExecChannelTestCase.java
@@ -26,11 +26,6 @@ import org.apache.commons.vfs2.ProviderWriteTests;
import junit.framework.Test;
public class SftpProviderClosedExecChannelTestCase extends AbstractSftpProviderTestCase {
- @Override
- protected boolean isExecChannelClosed() {
- return true;
- }
-
/**
* Creates the test suite for the sftp file system.
*/
@@ -49,4 +44,9 @@ public class SftpProviderClosedExecChannelTestCase extends AbstractSftpProviderT
};
return suite;
}
+
+ @Override
+ protected boolean isExecChannelClosed() {
+ return true;
+ }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/sftp/SftpProviderStreamProxyModeTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/sftp/SftpProviderStreamProxyModeTestCase.java
index 5874f1d..cf06773 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/sftp/SftpProviderStreamProxyModeTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/sftp/SftpProviderStreamProxyModeTestCase.java
@@ -29,11 +29,6 @@ import com.jcraft.jsch.TestIdentityRepositoryFactory;
import junit.framework.Test;
public class SftpProviderStreamProxyModeTestCase extends AbstractSftpProviderTestCase {
- @Override
- protected boolean isExecChannelClosed() {
- return false;
- }
-
// --- VFS-440: stream proxy test suite
// We override the addBaseTests method so that only
// one test is run (we just test that the input/output are correctly forwarded, and
@@ -97,4 +92,9 @@ public class SftpProviderStreamProxyModeTestCase extends AbstractSftpProviderTes
this.fileSystem = (SftpFileSystem) fileObject.getFileSystem();
return fileObject;
}
+
+ @Override
+ protected boolean isExecChannelClosed() {
+ return false;
+ }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/sftp/SftpProviderTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/sftp/SftpProviderTestCase.java
index c39065c..948f5e2 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/sftp/SftpProviderTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/sftp/SftpProviderTestCase.java
@@ -22,11 +22,6 @@ import junit.framework.Test;
public class SftpProviderTestCase extends AbstractSftpProviderTestCase {
- @Override
- protected boolean isExecChannelClosed() {
- return false;
- }
-
/**
* Creates the test suite for the sftp file system.
*/
@@ -37,4 +32,9 @@ public class SftpProviderTestCase extends AbstractSftpProviderTestCase {
suite.addTests(SftpMultiThreadWriteTests.class);
return suite;
}
+
+ @Override
+ protected boolean isExecChannelClosed() {
+ return false;
+ }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/CreateFileSystemTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/CreateFileSystemTestCase.java
index 8c19aae..ba76b9e 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/CreateFileSystemTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/CreateFileSystemTestCase.java
@@ -53,18 +53,18 @@ public class CreateFileSystemTestCase {
}
@Test
- public void testTgzFile() throws IOException {
+ public void testTbz2File() throws IOException {
- final String testFilePath = "src/test/resources/test-data/test.tgz";
+ final String testFilePath = "src/test/resources/test-data/test.tbz2";
try (FileObject fileObject = createFileSystem(testFilePath)) {
Assert.assertTrue(fileObject instanceof TarFileObject);
}
}
@Test
- public void testTbz2File() throws IOException {
+ public void testTgzFile() throws IOException {
- final String testFilePath = "src/test/resources/test-data/test.tbz2";
+ final String testFilePath = "src/test/resources/test-data/test.tgz";
try (FileObject fileObject = createFileSystem(testFilePath)) {
Assert.assertTrue(fileObject instanceof TarFileObject);
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/LargeTarTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/LargeTarTestCase.java
index d2c69c7..538a03f 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/LargeTarTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/LargeTarTestCase.java
@@ -46,86 +46,9 @@ import org.junit.Test;
public class LargeTarTestCase {
private final static String baseDir = "target/test-classes/test-data/";
- private DefaultFileSystemManager manager;
private final static String largeFilePath = baseDir;
private final static String largeFileName = "largefile";
-
- @Before
- public void setUp() throws Exception {
- manager = new DefaultFileSystemManager();
-
- manager.setFilesCache(new SoftRefFilesCache());
- manager.setCacheStrategy(CacheStrategy.ON_RESOLVE);
-
- manager.addProvider("file", new DefaultLocalFileProvider());
- manager.addProvider("tgz", new TarFileProvider());
- manager.addProvider("tar", new TarFileProvider());
-
- new File(baseDir).mkdir(); // if test is run standalone
- createLargeFile(largeFilePath, largeFileName);
- }
-
- @Test
- public void testLargeFile() throws Exception {
- final File realFile = new File(largeFilePath + largeFileName + ".tar.gz");
-
- final FileObject file = manager.resolveFile("tgz:file://" + realFile.getCanonicalPath() + "!/");
-
- assertNotNull(file);
- final List<FileObject> files = Arrays.asList(file.getChildren());
-
- assertNotNull(files);
- assertEquals(1, files.size());
- final FileObject f = files.get(0);
-
- assertEquals("Expected file not found: " + largeFileName + ".txt", f.getName().getBaseName(), largeFileName + ".txt");
- }
-
- /*
- * public void testFileCheck() throws Exception { String[] expectedFiles = { "plugins.tsv", "languages.tsv",
- * "browser_type.tsv", "timezones.tsv", "color_depth.tsv", "resolution.tsv", "connection_type.tsv",
- * "search_engines.tsv", "javascript_version.tsv", "operating_systems.tsv", "country.tsv", "browser.tsv" };
- *
- * fileCheck(expectedFiles, "tar:file://c:/temp/data/data/data-small.tar"); }
- */
-
- protected void fileCheck(final String[] expectedFiles, final String tarFile) throws Exception {
- assertNotNull(manager);
- final FileObject file = manager.resolveFile(tarFile);
-
- assertNotNull(file);
- final List<FileObject> files = Arrays.asList(file.getChildren());
-
- assertNotNull(files);
- for (final String expectedFile : expectedFiles) {
- assertTrue("Expected file not found: " + expectedFile, fileExists(expectedFile, files));
- }
- }
-
- /**
- * Search for the expected file in a given list, without using the full path.
- *
- * @param expectedFile the expected file.
- * @param files a list of files to search.
- * @return {@code true} if {@code expectedFile} is in {@code files}.
- */
- protected boolean fileExists(final String expectedFile, final List<FileObject> files) {
- for (final FileObject file : files) {
- if (file.getName().getBaseName().equals(expectedFile)) {
- return true;
- }
- }
- return false;
- }
-
- protected boolean endsWith(final String testString, final String[] testList) {
- for (final String string : testList) {
- if (testString.endsWith(string)) {
- return true;
- }
- }
- return false;
- }
+ private DefaultFileSystemManager manager;
// @SuppressWarnings("unused")
protected void createLargeFile(final String path, final String name) throws Exception {
@@ -190,4 +113,81 @@ public class LargeTarTestCase {
}
}
+
+ protected boolean endsWith(final String testString, final String[] testList) {
+ for (final String string : testList) {
+ if (testString.endsWith(string)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /*
+ * public void testFileCheck() throws Exception { String[] expectedFiles = { "plugins.tsv", "languages.tsv",
+ * "browser_type.tsv", "timezones.tsv", "color_depth.tsv", "resolution.tsv", "connection_type.tsv",
+ * "search_engines.tsv", "javascript_version.tsv", "operating_systems.tsv", "country.tsv", "browser.tsv" };
+ *
+ * fileCheck(expectedFiles, "tar:file://c:/temp/data/data/data-small.tar"); }
+ */
+
+ protected void fileCheck(final String[] expectedFiles, final String tarFile) throws Exception {
+ assertNotNull(manager);
+ final FileObject file = manager.resolveFile(tarFile);
+
+ assertNotNull(file);
+ final List<FileObject> files = Arrays.asList(file.getChildren());
+
+ assertNotNull(files);
+ for (final String expectedFile : expectedFiles) {
+ assertTrue("Expected file not found: " + expectedFile, fileExists(expectedFile, files));
+ }
+ }
+
+ /**
+ * Search for the expected file in a given list, without using the full path.
+ *
+ * @param expectedFile the expected file.
+ * @param files a list of files to search.
+ * @return {@code true} if {@code expectedFile} is in {@code files}.
+ */
+ protected boolean fileExists(final String expectedFile, final List<FileObject> files) {
+ for (final FileObject file : files) {
+ if (file.getName().getBaseName().equals(expectedFile)) {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ @Before
+ public void setUp() throws Exception {
+ manager = new DefaultFileSystemManager();
+
+ manager.setFilesCache(new SoftRefFilesCache());
+ manager.setCacheStrategy(CacheStrategy.ON_RESOLVE);
+
+ manager.addProvider("file", new DefaultLocalFileProvider());
+ manager.addProvider("tgz", new TarFileProvider());
+ manager.addProvider("tar", new TarFileProvider());
+
+ new File(baseDir).mkdir(); // if test is run standalone
+ createLargeFile(largeFilePath, largeFileName);
+ }
+
+ @Test
+ public void testLargeFile() throws Exception {
+ final File realFile = new File(largeFilePath + largeFileName + ".tar.gz");
+
+ final FileObject file = manager.resolveFile("tgz:file://" + realFile.getCanonicalPath() + "!/");
+
+ assertNotNull(file);
+ final List<FileObject> files = Arrays.asList(file.getChildren());
+
+ assertNotNull(files);
+ assertEquals(1, files.size());
+ final FileObject f = files.get(0);
+
+ assertEquals("Expected file not found: " + largeFileName + ".txt", f.getName().getBaseName(), largeFileName + ".txt");
+ }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/NestedTarTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/NestedTarTestCase.java
index 1254ce8..28c4e7a 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/NestedTarTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/NestedTarTestCase.java
@@ -40,16 +40,6 @@ public class NestedTarTestCase extends AbstractProviderTestConfig {
}
/**
- * Prepares the file system manager.
- */
- @Override
- public void prepare(final DefaultFileSystemManager manager) throws Exception {
- manager.addProvider("tar", new TarFileProvider());
- manager.addExtensionMap("tar", "tar");
- manager.addMimeTypeMap("application/x-tar", "tar");
- }
-
- /**
* Returns the base folder for tests.
*/
@Override
@@ -68,4 +58,14 @@ public class NestedTarTestCase extends AbstractProviderTestConfig {
final FileObject nestedFS = manager.createFileSystem(tarFile);
return nestedFS.resolveFile("/");
}
+
+ /**
+ * Prepares the file system manager.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager) throws Exception {
+ manager.addProvider("tar", new TarFileProvider());
+ manager.addExtensionMap("tar", "tar");
+ manager.addMimeTypeMap("application/x-tar", "tar");
+ }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/NestedTbz2TestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/NestedTbz2TestCase.java
index d1b9955..58684cf 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/NestedTbz2TestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/NestedTbz2TestCase.java
@@ -37,16 +37,6 @@ public class NestedTbz2TestCase extends AbstractProviderTestConfig {
}
/**
- * Prepares the file system manager.
- */
- @Override
- public void prepare(final DefaultFileSystemManager manager) throws Exception {
- manager.addProvider("tbz2", new TarFileProvider());
- manager.addExtensionMap("tbz2", "tbz2");
- manager.addProvider("tar", new TarFileProvider());
- }
-
- /**
* Returns the base folder for tests.
*/
@Override
@@ -60,4 +50,14 @@ public class NestedTbz2TestCase extends AbstractProviderTestConfig {
final FileObject nestedFS = manager.createFileSystem(tarFile);
return nestedFS.resolveFile("/");
}
+
+ /**
+ * Prepares the file system manager.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager) throws Exception {
+ manager.addProvider("tbz2", new TarFileProvider());
+ manager.addExtensionMap("tbz2", "tbz2");
+ manager.addProvider("tar", new TarFileProvider());
+ }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/NestedTgzTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/NestedTgzTestCase.java
index c182786..51b4f64 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/NestedTgzTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/NestedTgzTestCase.java
@@ -37,16 +37,6 @@ public class NestedTgzTestCase extends AbstractProviderTestConfig {
}
/**
- * Prepares the file system manager.
- */
- @Override
- public void prepare(final DefaultFileSystemManager manager) throws Exception {
- manager.addProvider("tgz", new TarFileProvider());
- manager.addExtensionMap("tgz", "tgz");
- manager.addProvider("tar", new TarFileProvider());
- }
-
- /**
* Returns the base folder for tests.
*/
@Override
@@ -60,4 +50,14 @@ public class NestedTgzTestCase extends AbstractProviderTestConfig {
final FileObject nestedFS = manager.createFileSystem(tarFile);
return nestedFS.resolveFile("/");
}
+
+ /**
+ * Prepares the file system manager.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager) throws Exception {
+ manager.addProvider("tgz", new TarFileProvider());
+ manager.addExtensionMap("tgz", "tgz");
+ manager.addProvider("tar", new TarFileProvider());
+ }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/TarFileObjectTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/TarFileObjectTestCase.java
index 3511179..3a48377 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/TarFileObjectTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/TarFileObjectTestCase.java
@@ -28,22 +28,33 @@ import org.junit.Test;
public class TarFileObjectTestCase {
- /**
- * Test read file with special name in a tar file
- */
- @Test
- public void testReadSpecialNameFileInTarFile() throws FileSystemException {
+ private void testReadSpecialNameFileInFile(final String testFilePath, final String scheme) throws FileSystemException {
- testReadSpecialNameFileInFile("src/test/resources/test-data/special_fileName.tar", "tar");
+ final File testFile = new File(testFilePath);
+ final String[] fileNames = {"file.txt", "file^.txt", "file~.txt", "file?.txt", "file@.txt", "file$.txt",
+ "file*.txt", "file&.txt", "file#.txt", "file%.txt", "file!.txt"};
+ final FileSystemManager manager = VFS.getManager();
+ final String baseUrl = scheme + ":file:" + testFile.getAbsolutePath();
+
+ // test
+ try (final FileObject fileObject = manager.resolveFile(baseUrl)) {
+ // test getChildren() number equal
+ Assert.assertEquals(fileObject.getChildren().length, fileNames.length);
+
+ // test getChild(String)
+ for (final String fileName : fileNames) {
+ Assert.assertNotNull("can't read file " + fileName, fileObject.getChild(fileName));
+ }
+ }
}
/**
- * Test read file with special name in a tgz file
+ * Test read file with special name in a tar file
*/
@Test
- public void testReadSpecialNameFileInTgzFile() throws FileSystemException {
+ public void testReadSpecialNameFileInTarFile() throws FileSystemException {
- testReadSpecialNameFileInFile("src/test/resources/test-data/special_fileName.tgz", "tgz");
+ testReadSpecialNameFileInFile("src/test/resources/test-data/special_fileName.tar", "tar");
}
/**
@@ -55,23 +66,12 @@ public class TarFileObjectTestCase {
testReadSpecialNameFileInFile("src/test/resources/test-data/special_fileName.tbz2", "tbz2");
}
- private void testReadSpecialNameFileInFile(final String testFilePath, final String scheme) throws FileSystemException {
-
- final File testFile = new File(testFilePath);
- final String[] fileNames = {"file.txt", "file^.txt", "file~.txt", "file?.txt", "file@.txt", "file$.txt",
- "file*.txt", "file&.txt", "file#.txt", "file%.txt", "file!.txt"};
- final FileSystemManager manager = VFS.getManager();
- final String baseUrl = scheme + ":file:" + testFile.getAbsolutePath();
-
- // test
- try (final FileObject fileObject = manager.resolveFile(baseUrl)) {
- // test getChildren() number equal
- Assert.assertEquals(fileObject.getChildren().length, fileNames.length);
+ /**
+ * Test read file with special name in a tgz file
+ */
+ @Test
+ public void testReadSpecialNameFileInTgzFile() throws FileSystemException {
- // test getChild(String)
- for (final String fileName : fileNames) {
- Assert.assertNotNull("can't read file " + fileName, fileObject.getChild(fileName));
- }
- }
+ testReadSpecialNameFileInFile("src/test/resources/test-data/special_fileName.tgz", "tgz");
}
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/TarProviderTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/TarProviderTestCase.java
index d76cbba..60a3a0a 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/TarProviderTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/TarProviderTestCase.java
@@ -39,15 +39,6 @@ public class TarProviderTestCase extends AbstractProviderTestConfig {
}
/**
- * Prepares the file system manager.
- */
- @Override
- public void prepare(final DefaultFileSystemManager manager) throws Exception {
- manager.addProvider("tar", new TarFileProvider());
- manager.addMimeTypeMap("application/x-tar", "tar");
- }
-
- /**
* Returns the base folder for read tests.
*/
@Override
@@ -56,4 +47,13 @@ public class TarProviderTestCase extends AbstractProviderTestConfig {
final String uri = "tar:file:" + tarFile.getAbsolutePath() + "!/";
return manager.resolveFile(uri);
}
+
+ /**
+ * Prepares the file system manager.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager) throws Exception {
+ manager.addProvider("tar", new TarFileProvider());
+ manager.addMimeTypeMap("application/x-tar", "tar");
+ }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/Tbz2ProviderTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/Tbz2ProviderTestCase.java
index e5cd886..8e5b257 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/Tbz2ProviderTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/Tbz2ProviderTestCase.java
@@ -39,15 +39,6 @@ public class Tbz2ProviderTestCase extends AbstractProviderTestConfig {
}
/**
- * Prepares the file system manager.
- */
- @Override
- public void prepare(final DefaultFileSystemManager manager) throws Exception {
- manager.addProvider("tbz2", new TarFileProvider());
- manager.addProvider("tar", new TarFileProvider());
- }
-
- /**
* Returns the base folder for read tests.
*/
@Override
@@ -56,4 +47,13 @@ public class Tbz2ProviderTestCase extends AbstractProviderTestConfig {
final String uri = "tbz2:file:" + tarFile.getAbsolutePath() + "!/";
return manager.resolveFile(uri);
}
+
+ /**
+ * Prepares the file system manager.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager) throws Exception {
+ manager.addProvider("tbz2", new TarFileProvider());
+ manager.addProvider("tar", new TarFileProvider());
+ }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/TgzProviderTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/TgzProviderTestCase.java
index c31870f..7c3fe41 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/TgzProviderTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/tar/TgzProviderTestCase.java
@@ -39,16 +39,6 @@ public class TgzProviderTestCase extends AbstractProviderTestConfig {
}
/**
- * Prepares the file system manager.
- */
- @Override
- public void prepare(final DefaultFileSystemManager manager) throws Exception {
- // manager.addProvider("tgz", new TgzFileProvider());
- manager.addProvider("tgz", new TarFileProvider());
- manager.addProvider("tar", new TarFileProvider());
- }
-
- /**
* Returns the base folder for read tests.
*/
@Override
@@ -57,4 +47,14 @@ public class TgzProviderTestCase extends AbstractProviderTestConfig {
final String uri = "tgz:file:" + tarFile.getAbsolutePath() + "!/";
return manager.resolveFile(uri);
}
+
+ /**
+ * Prepares the file system manager.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager) throws Exception {
+ // manager.addProvider("tgz", new TgzFileProvider());
+ manager.addProvider("tgz", new TarFileProvider());
+ manager.addProvider("tar", new TarFileProvider());
+ }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/temp/TemporaryProviderTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/temp/TemporaryProviderTestCase.java
index 844fe57..f959dcd 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/temp/TemporaryProviderTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/temp/TemporaryProviderTestCase.java
@@ -39,19 +39,19 @@ public class TemporaryProviderTestCase extends AbstractProviderTestConfig {
}
/**
- * Prepares the file system manager.
+ * Returns the base folder for tests.
*/
@Override
- public void prepare(final DefaultFileSystemManager manager) throws Exception {
- final File baseDir = AbstractVfsTestCase.getTestDirectoryFile();
- manager.addProvider("tmp", new TemporaryFileProvider(baseDir));
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
+ return manager.resolveFile("tmp:/");
}
/**
- * Returns the base folder for tests.
+ * Prepares the file system manager.
*/
@Override
- public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
- return manager.resolveFile("tmp:/");
+ public void prepare(final DefaultFileSystemManager manager) throws Exception {
+ final File baseDir = AbstractVfsTestCase.getTestDirectoryFile();
+ manager.addProvider("tmp", new TemporaryFileProvider(baseDir));
}
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/test/GenericFileNameTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/test/GenericFileNameTestCase.java
index ad79e87..acb1194 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/test/GenericFileNameTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/test/GenericFileNameTestCase.java
@@ -28,6 +28,43 @@ import org.junit.Test;
public class GenericFileNameTestCase extends AbstractVfsTestCase {
/**
+ * Tests error handling in URI parser.
+ */
+ @Test
+ public void testBadlyFormedUri() throws Exception {
+ // Does not start with ftp://
+ testBadlyFormedUri("ftp:", "vfs.provider/missing-double-slashes.error");
+ testBadlyFormedUri("ftp:/", "vfs.provider/missing-double-slashes.error");
+ testBadlyFormedUri("ftp:a", "vfs.provider/missing-double-slashes.error");
+
+ // Missing hostname
+ testBadlyFormedUri("ftp://", "vfs.provider/missing-hostname.error");
+ testBadlyFormedUri("ftp://:21/file", "vfs.provider/missing-hostname.error");
+ testBadlyFormedUri("ftp:///file", "vfs.provider/missing-hostname.error");
+
+ // Empty port
+ testBadlyFormedUri("ftp://host:", "vfs.provider/missing-port.error");
+ testBadlyFormedUri("ftp://host:/file", "vfs.provider/missing-port.error");
+ testBadlyFormedUri("ftp://host:port/file", "vfs.provider/missing-port.error");
+
+ // Missing absolute path
+ testBadlyFormedUri("ftp://host:90a", "vfs.provider/missing-hostname-path-sep.error");
+ testBadlyFormedUri("ftp://host?a", "vfs.provider/missing-hostname-path-sep.error");
+ }
+
+ /**
+ * Tests that parsing a URI fails with the expected error.
+ */
+ private void testBadlyFormedUri(final String uri, final String errorMsg) {
+ try {
+ new URLFileNameParser(80).parseUri(null, null, uri);
+ fail();
+ } catch (final FileSystemException e) {
+ assertSameMessage(errorMsg, uri, e);
+ }
+ }
+
+ /**
* Tests parsing a URI into its parts.
*/
@Test
@@ -100,41 +137,4 @@ public class GenericFileNameTestCase extends AbstractVfsTestCase {
assertEquals("ftp://user%3a:%40@hostname/", name.getRootURI());
assertEquals("ftp://user%3a:%40@hostname/", name.getURI());
}
-
- /**
- * Tests error handling in URI parser.
- */
- @Test
- public void testBadlyFormedUri() throws Exception {
- // Does not start with ftp://
- testBadlyFormedUri("ftp:", "vfs.provider/missing-double-slashes.error");
- testBadlyFormedUri("ftp:/", "vfs.provider/missing-double-slashes.error");
- testBadlyFormedUri("ftp:a", "vfs.provider/missing-double-slashes.error");
-
- // Missing hostname
- testBadlyFormedUri("ftp://", "vfs.provider/missing-hostname.error");
- testBadlyFormedUri("ftp://:21/file", "vfs.provider/missing-hostname.error");
- testBadlyFormedUri("ftp:///file", "vfs.provider/missing-hostname.error");
-
- // Empty port
- testBadlyFormedUri("ftp://host:", "vfs.provider/missing-port.error");
- testBadlyFormedUri("ftp://host:/file", "vfs.provider/missing-port.error");
- testBadlyFormedUri("ftp://host:port/file", "vfs.provider/missing-port.error");
-
- // Missing absolute path
- testBadlyFormedUri("ftp://host:90a", "vfs.provider/missing-hostname-path-sep.error");
- testBadlyFormedUri("ftp://host?a", "vfs.provider/missing-hostname-path-sep.error");
- }
-
- /**
- * Tests that parsing a URI fails with the expected error.
- */
- private void testBadlyFormedUri(final String uri, final String errorMsg) {
- try {
- new URLFileNameParser(80).parseUri(null, null, uri);
- fail();
- } catch (final FileSystemException e) {
- assertSameMessage(errorMsg, uri, e);
- }
- }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/test/JunctionProviderConfig.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/test/JunctionProviderConfig.java
index 0ec862c..cff7ae9 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/test/JunctionProviderConfig.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/test/JunctionProviderConfig.java
@@ -34,6 +34,21 @@ public class JunctionProviderConfig implements ProviderTestConfig {
}
/**
+ * Returns the base folder for tests.
+ */
+ @Override
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
+ final FileObject baseFolder = config.getBaseTestFolder(manager);
+
+ // Create an empty file system, then link in the base folder
+ final FileSystem newFs = manager.createVirtualFileSystem("vfs:").getFileSystem();
+ final String junctionPoint = "/some/dir";
+ newFs.addJunction(junctionPoint, baseFolder);
+
+ return newFs.resolveFile(junctionPoint);
+ }
+
+ /**
* Returns a DefaultFileSystemManager instance (or subclass instance).
*/
@Override
@@ -46,31 +61,16 @@ public class JunctionProviderConfig implements ProviderTestConfig {
return config.getFilesCache();
}
- /**
- * Prepares the file system manager.
- */
@Override
- public void prepare(final DefaultFileSystemManager manager) throws Exception {
- config.prepare(manager);
+ public boolean isFileSystemRootAccessible() {
+ return true;
}
/**
- * Returns the base folder for tests.
+ * Prepares the file system manager.
*/
@Override
- public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
- final FileObject baseFolder = config.getBaseTestFolder(manager);
-
- // Create an empty file system, then link in the base folder
- final FileSystem newFs = manager.createVirtualFileSystem("vfs:").getFileSystem();
- final String junctionPoint = "/some/dir";
- newFs.addJunction(junctionPoint, baseFolder);
-
- return newFs.resolveFile(junctionPoint);
- }
-
- @Override
- public boolean isFileSystemRootAccessible() {
- return true;
+ public void prepare(final DefaultFileSystemManager manager) throws Exception {
+ config.prepare(manager);
}
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/test/JunctionTests.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/test/JunctionTests.java
index 47ada65..f5878b9 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/test/JunctionTests.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/test/JunctionTests.java
@@ -37,32 +37,6 @@ public class JunctionTests extends AbstractProviderTestCase {
}
/**
- * Checks nested junctions are not supported.
- */
- @Test
- public void testNestedJunction() throws Exception {
- final FileSystem fs = getManager().createVirtualFileSystem("vfs:").getFileSystem();
- final FileObject baseDir = getBaseDir();
- fs.addJunction("/a", baseDir);
-
- // Nested
- try {
- fs.addJunction("/a/b", baseDir);
- fail();
- } catch (final Exception e) {
- assertSameMessage("vfs.impl/nested-junction.error", "vfs:/a/b", e);
- }
-
- // At same point
- try {
- fs.addJunction("/a", baseDir);
- fail();
- } catch (final Exception e) {
- assertSameMessage("vfs.impl/nested-junction.error", "vfs:/a", e);
- }
- }
-
- /**
* Checks ancestors are created when a junction is created.
*/
@Test
@@ -90,6 +64,32 @@ public class JunctionTests extends AbstractProviderTestCase {
assertTrue("Does not exist", file.exists());
}
+ /**
+ * Checks nested junctions are not supported.
+ */
+ @Test
+ public void testNestedJunction() throws Exception {
+ final FileSystem fs = getManager().createVirtualFileSystem("vfs:").getFileSystem();
+ final FileObject baseDir = getBaseDir();
+ fs.addJunction("/a", baseDir);
+
+ // Nested
+ try {
+ fs.addJunction("/a/b", baseDir);
+ fail();
+ } catch (final Exception e) {
+ assertSameMessage("vfs.impl/nested-junction.error", "vfs:/a/b", e);
+ }
+
+ // At same point
+ try {
+ fs.addJunction("/a", baseDir);
+ fail();
+ } catch (final Exception e) {
+ assertSameMessage("vfs.impl/nested-junction.error", "vfs:/a", e);
+ }
+ }
+
// Check that file @ junction point exists only when backing file exists
// Add 2 junctions with common parent
// Compare real and virtual files
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/url/UrlHttpProviderTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/url/UrlHttpProviderTestCase.java
index acd1938..a145f2a 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/url/UrlHttpProviderTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/url/UrlHttpProviderTestCase.java
@@ -36,19 +36,19 @@ public class UrlHttpProviderTestCase extends AbstractProviderTestConfig {
}
/**
- * Prepares the file system manager. This implementation does nothing.
+ * Returns the base folder for tests.
*/
@Override
- public void prepare(final DefaultFileSystemManager manager) throws Exception {
- manager.addProvider("http", new UrlFileProvider());
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
+ final File baseDir = AbstractVfsTestCase.getTestDirectoryFile();
+ return manager.resolveFile(baseDir.toURI().toURL().toExternalForm());
}
/**
- * Returns the base folder for tests.
+ * Prepares the file system manager. This implementation does nothing.
*/
@Override
- public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
- final File baseDir = AbstractVfsTestCase.getTestDirectoryFile();
- return manager.resolveFile(baseDir.toURI().toURL().toExternalForm());
+ public void prepare(final DefaultFileSystemManager manager) throws Exception {
+ manager.addProvider("http", new UrlFileProvider());
}
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/url/UrlProviderTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/url/UrlProviderTestCase.java
index 438e7a9..d337eb0 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/url/UrlProviderTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/url/UrlProviderTestCase.java
@@ -36,19 +36,19 @@ public class UrlProviderTestCase extends AbstractProviderTestConfig {
}
/**
- * Prepares the file system manager. This implementation does nothing.
+ * Returns the base folder for tests.
*/
@Override
- public void prepare(final DefaultFileSystemManager manager) throws Exception {
- manager.addProvider("file", new UrlFileProvider());
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
+ final File baseDir = AbstractVfsTestCase.getTestDirectoryFile();
+ return manager.resolveFile(baseDir.toURI().toURL().toExternalForm());
}
/**
- * Returns the base folder for tests.
+ * Prepares the file system manager. This implementation does nothing.
*/
@Override
- public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
- final File baseDir = AbstractVfsTestCase.getTestDirectoryFile();
- return manager.resolveFile(baseDir.toURI().toURL().toExternalForm());
+ public void prepare(final DefaultFileSystemManager manager) throws Exception {
+ manager.addProvider("file", new UrlFileProvider());
}
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/FileLockTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/FileLockTestCase.java
index 87d4d53..2a2f476 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/FileLockTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/FileLockTestCase.java
@@ -49,6 +49,12 @@ public class FileLockTestCase {
Assert.assertTrue("Could not delete file", newZipFile.delete());
}
+ private void readAndAssert(final InputStream inputStream) throws IOException {
+ final String string = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
+ Assert.assertNotNull(string);
+ Assert.assertEquals("This is a test file.", string);
+ }
+
private void resolveAndOpenCloseContent() throws FileSystemException {
try (final FileObject zipFileObject = manager.resolveFile(zipFileUri)) {
zipFileObject.getContent().close();
@@ -69,12 +75,6 @@ public class FileLockTestCase {
}
}
- private void readAndAssert(final InputStream inputStream) throws IOException {
- final String string = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
- Assert.assertNotNull(string);
- Assert.assertEquals("This is a test file.", string);
- }
-
@Before
public void setup() throws IOException {
final File zipFile = new File("src/test/resources/test-data/test.zip");
@@ -110,22 +110,25 @@ public class FileLockTestCase {
}
@Test
- public void testResolveAndOpenCloseContent() throws Exception {
- resolveAndOpenCloseContent();
- assertDelete();
- }
-
- @Test
- public void testResolveAndOpenReadCloseInputStream() throws Exception {
- resolveAndOpenReadCloseInputStream();
+ public void testReadClosedFileObject() throws Exception {
+ final FileObject zipFileObjectRef;
+ try (final FileObject zipFileObject = manager.resolveFile(zipFileUri)) {
+ zipFileObjectRef = zipFileObject;
+ try (final InputStream inputStream = zipFileObject.getContent().getInputStream()) {
+ readAndAssert(inputStream);
+ }
+ }
+ try (final InputStream inputStream = zipFileObjectRef.getContent().getInputStream()) {
+ readAndAssert(inputStream);
+ } finally {
+ zipFileObjectRef.close();
+ }
assertDelete();
}
@Test
- public void testResolveAndOpenReadCloseInputStream3() throws Exception {
- resolveAndOpenReadCloseInputStream();
- resolveAndOpenReadCloseInputStream();
- resolveAndOpenReadCloseInputStream();
+ public void testResolveAndOpenCloseContent() throws Exception {
+ resolveAndOpenCloseContent();
assertDelete();
}
@@ -160,29 +163,26 @@ public class FileLockTestCase {
}
@Test
- public void testResolveOpenCloseNestedInputStreams() throws Exception {
- try (final FileObject zipFileObject = manager.resolveFile(zipFileUri)) {
- try (final FileObject zipFileObject2 = manager.resolveFile(zipFileUri)) {
- zipFileObject2.getContent().getInputStream().close();
- }
- zipFileObject.getContent().getInputStream().close();
- }
+ public void testResolveAndOpenReadCloseInputStream() throws Exception {
+ resolveAndOpenReadCloseInputStream();
assertDelete();
}
@Test
- public void testReadClosedFileObject() throws Exception {
- final FileObject zipFileObjectRef;
+ public void testResolveAndOpenReadCloseInputStream3() throws Exception {
+ resolveAndOpenReadCloseInputStream();
+ resolveAndOpenReadCloseInputStream();
+ resolveAndOpenReadCloseInputStream();
+ assertDelete();
+ }
+
+ @Test
+ public void testResolveOpenCloseNestedInputStreams() throws Exception {
try (final FileObject zipFileObject = manager.resolveFile(zipFileUri)) {
- zipFileObjectRef = zipFileObject;
- try (final InputStream inputStream = zipFileObject.getContent().getInputStream()) {
- readAndAssert(inputStream);
+ try (final FileObject zipFileObject2 = manager.resolveFile(zipFileUri)) {
+ zipFileObject2.getContent().getInputStream().close();
}
- }
- try (final InputStream inputStream = zipFileObjectRef.getContent().getInputStream()) {
- readAndAssert(inputStream);
- } finally {
- zipFileObjectRef.close();
+ zipFileObject.getContent().getInputStream().close();
}
assertDelete();
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/NestedZipTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/NestedZipTestCase.java
index 846d823..14add05 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/NestedZipTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/NestedZipTestCase.java
@@ -37,16 +37,6 @@ public class NestedZipTestCase extends AbstractProviderTestConfig {
}
/**
- * Prepares the file system manager.
- */
- @Override
- public void prepare(final DefaultFileSystemManager manager) throws Exception {
- manager.addProvider("zip", new ZipFileProvider());
- manager.addExtensionMap("zip", "zip");
- manager.addMimeTypeMap("application/zip", "zip");
- }
-
- /**
* Returns the base folder for tests.
*/
@Override
@@ -60,4 +50,14 @@ public class NestedZipTestCase extends AbstractProviderTestConfig {
final FileObject nestedFS = manager.createFileSystem(zipFile);
return nestedFS.resolveFile("/");
}
+
+ /**
+ * Prepares the file system manager.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager) throws Exception {
+ manager.addProvider("zip", new ZipFileProvider());
+ manager.addExtensionMap("zip", "zip");
+ manager.addMimeTypeMap("application/zip", "zip");
+ }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/ParseXmlInZipTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/ParseXmlInZipTestCase.java
index 51ed259..6e96fa5 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/ParseXmlInZipTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/ParseXmlInZipTestCase.java
@@ -47,6 +47,15 @@ public class ParseXmlInZipTestCase {
private Locale defaultLocale;
+ @Before
+ public void changeDefaultLocale() {
+ // save origin default Locale
+ defaultLocale = Locale.getDefault();
+
+ // change default Locale to US. Prevent Regular Matching fail.
+ Locale.setDefault(new Locale("en", "US"));
+ }
+
private File createTempFile() throws IOException {
final File zipFile = new File("src/test/resources/test-data/read-xml-tests.zip");
final File newZipFile = File.createTempFile(getClass().getSimpleName(), ".zip");
@@ -84,15 +93,6 @@ public class ParseXmlInZipTestCase {
return documentBuilder;
}
- @Before
- public void changeDefaultLocale() {
- // save origin default Locale
- defaultLocale = Locale.getDefault();
-
- // change default Locale to US. Prevent Regular Matching fail.
- Locale.setDefault(new Locale("en", "US"));
- }
-
@After
public void resetDefaultLocale() {
Locale.setDefault(defaultLocale);
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/ZipFileObjectTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/ZipFileObjectTestCase.java
index c47f328..3d53cb1 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/ZipFileObjectTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/ZipFileObjectTestCase.java
@@ -65,6 +65,15 @@ public class ZipFileObjectTestCase {
streamData);
}
+ private void resolveReadAssert(final FileObject zipFileObject, final String path)
+ throws IOException, FileSystemException {
+ try (final FileObject zipFileObject2 = zipFileObject.resolveFile(path)) {
+ try (final InputStream inputStream = zipFileObject2.getContent().getInputStream()) {
+ readAndAssert(zipFileObject2, inputStream, "2");
+ }
+ }
+ }
+
/**
* Tests that when we read a file inside a file Zip and leave it open, we can still delete the Zip after we clean up
* the Zip file.
@@ -104,15 +113,6 @@ public class ZipFileObjectTestCase {
assertDelete(newZipFile);
}
- private void resolveReadAssert(final FileObject zipFileObject, final String path)
- throws IOException, FileSystemException {
- try (final FileObject zipFileObject2 = zipFileObject.resolveFile(path)) {
- try (final InputStream inputStream = zipFileObject2.getContent().getInputStream()) {
- readAndAssert(zipFileObject2, inputStream, "2");
- }
- }
- }
-
/**
* Tests that we can get a stream from one file in a zip file, then close another file from the same zip, then
* process the initial input stream.
@@ -164,24 +164,6 @@ public class ZipFileObjectTestCase {
}
/**
- * Tests that we can resolve a file in a Zip file, then close the container zip, which should still let us delete
- * the Zip file.
- *
- * @throws IOException
- */
- @Test
- public void testResolveNestedFileWithoutCleanup() throws IOException {
- final File newZipFile = createTempFile();
- final FileSystemManager manager = VFS.getManager();
- try (final FileObject zipFileObject = manager.resolveFile("zip:file:" + newZipFile.getAbsolutePath())) {
- @SuppressWarnings({ "unused", "resource" })
- // We resolve a nested file and do nothing else.
- final FileObject zipFileObject1 = zipFileObject.resolveFile(NESTED_FILE_1);
- }
- assertDelete(newZipFile);
- }
-
- /**
* Test read file with special name in a zip file
*/
@Test
@@ -204,4 +186,22 @@ public class ZipFileObjectTestCase {
}
}
}
+
+ /**
+ * Tests that we can resolve a file in a Zip file, then close the container zip, which should still let us delete
+ * the Zip file.
+ *
+ * @throws IOException
+ */
+ @Test
+ public void testResolveNestedFileWithoutCleanup() throws IOException {
+ final File newZipFile = createTempFile();
+ final FileSystemManager manager = VFS.getManager();
+ try (final FileObject zipFileObject = manager.resolveFile("zip:file:" + newZipFile.getAbsolutePath())) {
+ @SuppressWarnings({ "unused", "resource" })
+ // We resolve a nested file and do nothing else.
+ final FileObject zipFileObject1 = zipFileObject.resolveFile(NESTED_FILE_1);
+ }
+ assertDelete(newZipFile);
+ }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/ZipProviderTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/ZipProviderTestCase.java
index 168009d..ca2c9f2 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/ZipProviderTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/ZipProviderTestCase.java
@@ -39,16 +39,6 @@ public class ZipProviderTestCase extends AbstractProviderTestConfig {
}
/**
- * Prepares the file system manager.
- */
- @Override
- public void prepare(final DefaultFileSystemManager manager) throws Exception {
- manager.addProvider("zip", new ZipFileProvider());
- manager.addExtensionMap("zip", "zip");
- manager.addMimeTypeMap("application/zip", "zip");
- }
-
- /**
* Returns the base folder for read tests.
*/
@Override
@@ -57,4 +47,14 @@ public class ZipProviderTestCase extends AbstractProviderTestConfig {
final String uri = "zip:file:" + zipFile.getAbsolutePath() + "!/";
return manager.resolveFile(uri);
}
+
+ /**
+ * Prepares the file system manager.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager) throws Exception {
+ manager.addProvider("zip", new ZipFileProvider());
+ manager.addExtensionMap("zip", "zip");
+ manager.addMimeTypeMap("application/zip", "zip");
+ }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/ZipProviderWithCharsetNullTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/ZipProviderWithCharsetNullTestCase.java
index 73c7b80..3fe9db2 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/ZipProviderWithCharsetNullTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/ZipProviderWithCharsetNullTestCase.java
@@ -42,16 +42,6 @@ public class ZipProviderWithCharsetNullTestCase extends AbstractProviderTestConf
}
/**
- * Prepares the file system manager.
- */
- @Override
- public void prepare(final DefaultFileSystemManager manager) throws Exception {
- manager.addProvider("zip", new ZipFileProvider());
- manager.addExtensionMap("zip", "zip");
- manager.addMimeTypeMap("application/zip", "zip");
- }
-
- /**
* Returns the base folder for read tests.
*/
@Override
@@ -70,4 +60,14 @@ public class ZipProviderWithCharsetNullTestCase extends AbstractProviderTestConf
Assert.assertNull(zipFileSystem.getCharset());
return resolvedFile;
}
+
+ /**
+ * Prepares the file system manager.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager) throws Exception {
+ manager.addProvider("zip", new ZipFileProvider());
+ manager.addExtensionMap("zip", "zip");
+ manager.addMimeTypeMap("application/zip", "zip");
+ }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/ZipProviderWithCharsetTestCase.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/ZipProviderWithCharsetTestCase.java
index 0569924..c20564e 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/ZipProviderWithCharsetTestCase.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/provider/zip/ZipProviderWithCharsetTestCase.java
@@ -43,16 +43,6 @@ public class ZipProviderWithCharsetTestCase extends AbstractProviderTestConfig {
}
/**
- * Prepares the file system manager.
- */
- @Override
- public void prepare(final DefaultFileSystemManager manager) throws Exception {
- manager.addProvider("zip", new ZipFileProvider());
- manager.addExtensionMap("zip", "zip");
- manager.addMimeTypeMap("application/zip", "zip");
- }
-
- /**
* Returns the base folder for read tests.
*/
@Override
@@ -71,4 +61,14 @@ public class ZipProviderWithCharsetTestCase extends AbstractProviderTestConfig {
Assert.assertEquals(StandardCharsets.UTF_8, zipFileSystem.getCharset());
return resolvedFile;
}
+
+ /**
+ * Prepares the file system manager.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager) throws Exception {
+ manager.addProvider("zip", new ZipFileProvider());
+ manager.addExtensionMap("zip", "zip");
+ manager.addMimeTypeMap("application/zip", "zip");
+ }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/util/DelegatingFileSystemOptionsBuilderTest.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/util/DelegatingFileSystemOptionsBuilderTest.java
index df75b9d..2b0c666 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/util/DelegatingFileSystemOptionsBuilderTest.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/util/DelegatingFileSystemOptionsBuilderTest.java
@@ -39,6 +39,9 @@ import org.junit.Test;
* Some tests for the DelegatingFileSystemOptionsBuilder
*/
public class DelegatingFileSystemOptionsBuilderTest {
+ private static final String[] schemes = new String[] { "http", "ftp", "file", "zip", "tar", "tgz", "bz2", "gz",
+ "jar", "tmp", "ram" };
+
private StandardFileSystemManager fsm;
@Before
@@ -57,28 +60,9 @@ public class DelegatingFileSystemOptionsBuilderTest {
}
@Test
- public void testDelegatingGood() throws Throwable {
- final String[] identityPaths = new String[] { "/file1", "/file2", };
-
- final FileSystemOptions opts = new FileSystemOptions();
- final DelegatingFileSystemOptionsBuilder delgate = new DelegatingFileSystemOptionsBuilder(fsm);
-
- delgate.setConfigString(opts, "http", "proxyHost", "proxy");
- delgate.setConfigString(opts, "http", "proxyPort", "8080");
- delgate.setConfigClass(opts, "sftp", "userinfo", TrustEveryoneUserInfo.class);
- delgate.setConfigStrings(opts, "sftp", "identities", identityPaths);
-
- assertEquals("http.proxyHost", HttpFileSystemConfigBuilder.getInstance().getProxyHost(opts), "proxy");
- assertEquals("http.proxyPort", HttpFileSystemConfigBuilder.getInstance().getProxyPort(opts), 8080);
- assertSame("sftp.userInfo", SftpFileSystemConfigBuilder.getInstance().getUserInfo(opts).getClass(),
- TrustEveryoneUserInfo.class);
-
- final File[] identities = SftpFileSystemConfigBuilder.getInstance().getIdentities(opts);
- assertNotNull("sftp.identities", identities);
- assertEquals("sftp.identities size", identities.length, identityPaths.length);
- for (int iterIdentities = 0; iterIdentities < identities.length; iterIdentities++) {
- assertEquals("sftp.identities #" + iterIdentities, identities[iterIdentities].getAbsolutePath(),
- new File(identityPaths[iterIdentities]).getAbsolutePath());
+ public void testConfiguration() throws Exception {
+ for (final String scheme : schemes) {
+ assertTrue("Missing " + scheme + " provider", fsm.hasProvider(scheme));
}
}
@@ -104,13 +88,29 @@ public class DelegatingFileSystemOptionsBuilderTest {
}
}
- private static final String[] schemes = new String[] { "http", "ftp", "file", "zip", "tar", "tgz", "bz2", "gz",
- "jar", "tmp", "ram" };
-
@Test
- public void testConfiguration() throws Exception {
- for (final String scheme : schemes) {
- assertTrue("Missing " + scheme + " provider", fsm.hasProvider(scheme));
+ public void testDelegatingGood() throws Throwable {
+ final String[] identityPaths = new String[] { "/file1", "/file2", };
+
+ final FileSystemOptions opts = new FileSystemOptions();
+ final DelegatingFileSystemOptionsBuilder delgate = new DelegatingFileSystemOptionsBuilder(fsm);
+
+ delgate.setConfigString(opts, "http", "proxyHost", "proxy");
+ delgate.setConfigString(opts, "http", "proxyPort", "8080");
+ delgate.setConfigClass(opts, "sftp", "userinfo", TrustEveryoneUserInfo.class);
+ delgate.setConfigStrings(opts, "sftp", "identities", identityPaths);
+
+ assertEquals("http.proxyHost", HttpFileSystemConfigBuilder.getInstance().getProxyHost(opts), "proxy");
+ assertEquals("http.proxyPort", HttpFileSystemConfigBuilder.getInstance().getProxyPort(opts), 8080);
+ assertSame("sftp.userInfo", SftpFileSystemConfigBuilder.getInstance().getUserInfo(opts).getClass(),
+ TrustEveryoneUserInfo.class);
+
+ final File[] identities = SftpFileSystemConfigBuilder.getInstance().getIdentities(opts);
+ assertNotNull("sftp.identities", identities);
+ assertEquals("sftp.identities size", identities.length, identityPaths.length);
+ for (int iterIdentities = 0; iterIdentities < identities.length; iterIdentities++) {
+ assertEquals("sftp.identities #" + iterIdentities, identities[iterIdentities].getAbsolutePath(),
+ new File(identityPaths[iterIdentities]).getAbsolutePath());
}
}
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/util/FreeSocketPortUtil.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/util/FreeSocketPortUtil.java
index 118ea2c..206c850 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/util/FreeSocketPortUtil.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/util/FreeSocketPortUtil.java
@@ -22,10 +22,6 @@ import java.net.ServerSocket;
public class FreeSocketPortUtil {
- public static void main(final String[] args) throws IOException {
- System.out.println(FreeSocketPortUtil.findFreeLocalPort());
- }
-
/**
* Finds a free local socket port.
*
@@ -37,4 +33,8 @@ public class FreeSocketPortUtil {
return server.getLocalPort();
}
}
+
+ public static void main(final String[] args) throws IOException {
+ System.out.println(FreeSocketPortUtil.findFreeLocalPort());
+ }
}
diff --git a/commons-vfs2/src/test/java/org/apache/commons/vfs2/util/NHttpFileServer.java b/commons-vfs2/src/test/java/org/apache/commons/vfs2/util/NHttpFileServer.java
index 3e1a755..a84ddd4 100644
--- a/commons-vfs2/src/test/java/org/apache/commons/vfs2/util/NHttpFileServer.java
+++ b/commons-vfs2/src/test/java/org/apache/commons/vfs2/util/NHttpFileServer.java
@@ -205,6 +205,15 @@ public class NHttpFileServer {
server.awaitShutdown(TimeValue.MAX_VALUE);
}
+ public void close() {
+ if (server.getStatus() == IOReactorStatus.ACTIVE) {
+ final CloseMode closeMode = CloseMode.GRACEFUL;
+ println("HTTP server shutting down (closeMode=" + closeMode + ")...");
+ server.close(closeMode);
+ println("HTTP server shut down.");
+ }
+ }
+
public int getPort() {
if (server == null) {
return port;
@@ -263,13 +272,4 @@ public class NHttpFileServer {
return this;
}
- public void close() {
- if (server.getStatus() == IOReactorStatus.ACTIVE) {
- final CloseMode closeMode = CloseMode.GRACEFUL;
- println("HTTP server shutting down (closeMode=" + closeMode + ")...");
- server.close(closeMode);
- println("HTTP server shut down.");
- }
- }
-
}