[maven-release-plugin] copy for tag commons-vfs2-project-2.1
git-svn-id: https://svn.apache.org/repos/asf/commons/proper/vfs/tags/commons-vfs2-project-2.1@1741913 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/trunk/.gitignore b/trunk/.gitignore
new file mode 100644
index 0000000..838eb26
--- /dev/null
+++ b/trunk/.gitignore
@@ -0,0 +1,5 @@
+target/
+.project
+.classpath
+.settings/
+.svn/
diff --git a/trunk/CONTRIBUTING.md b/trunk/CONTRIBUTING.md
new file mode 100644
index 0000000..bfafdd8
--- /dev/null
+++ b/trunk/CONTRIBUTING.md
@@ -0,0 +1,97 @@
+<!---
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<!---
+ +======================================================================+
+ |**** ****|
+ |**** THIS FILE IS GENERATED BY THE COMMONS BUILD PLUGIN ****|
+ |**** DO NOT EDIT DIRECTLY ****|
+ |**** ****|
+ +======================================================================+
+ | TEMPLATE FILE: contributing-md-template.md |
+ | commons-build-plugin/trunk/src/main/resources/commons-xdoc-templates |
+ +======================================================================+
+ | |
+ | 1) Re-generate using: mvn commons:contributing-md |
+ | |
+ | 2) Set the following properties in the component's pom: |
+ | - commons.jira.id (required, alphabetic, upper case) |
+ | |
+ | 3) Example Properties |
+ | |
+ | <properties> |
+ | <commons.jira.id>MATH</commons.jira.id> |
+ | </properties> |
+ | |
+ +======================================================================+
+--->
+Contributing to Apache Commons VFS
+======================
+
+You have found a bug or you have an idea for a cool new feature? Contributing code is a great way to give something back to
+the open source community. Before you dig right into the code there are a few guidelines that we need contributors to
+follow so that we can have a chance of keeping on top of things.
+
+Getting Started
+---------------
+
++ Make sure you have a [JIRA account](https://issues.apache.org/jira/).
++ Make sure you have a [GitHub account](https://github.com/signup/free).
++ If you're planning to implement a new feature it makes sense to discuss you're changes on the [dev list](http://commons.apache.org/proper/commons-vfs/mail-lists.html) first. This way you can make sure you're not wasting your time on something that isn't considered to be in Apache Commons VFS's scope.
++ Submit a ticket for your issue, assuming one does not already exist.
+ + Clearly describe the issue including steps to reproduce when it is a bug.
+ + Make sure you fill in the earliest version that you know has the issue.
++ Fork the repository on GitHub.
+
+Making Changes
+--------------
+
++ Create a topic branch from where you want to base your work (this is usually the master/trunk branch).
++ Make commits of logical units.
++ Respect the original code style:
+ + Only use spaces for indentation.
+ + Create minimal diffs - disable on save actions like reformat source code or organize imports. If you feel the source code should be reformatted create a separate PR for this change.
+ + Check for unnecessary whitespace with git diff --check before committing.
++ Make sure your commit messages are in the proper format. Your commit message should contain the key of the JIRA issue.
++ Make sure you have added the necessary tests for your changes.
++ Run all the tests with `mvn clean verify` to assure nothing else was accidentally broken.
+
+Making Trivial Changes
+----------------------
+
+For changes of a trivial nature to comments and documentation, it is not always necessary to create a new ticket in JIRA.
+In this case, it is appropriate to start the first line of a commit with '(doc)' instead of a ticket number.
+
+Submitting Changes
+------------------
+
++ Sign the [Contributor License Agreement][cla] if you haven't already.
++ Push your changes to a topic branch in your fork of the repository.
++ Submit a pull request to the repository in the apache organization.
++ Update your JIRA ticket and include a link to the pull request in the ticket.
+
+Additional Resources
+--------------------
+
++ [Contributing patches](http://commons.apache.org/patches.html)
++ [Apache Commons VFS JIRA project page](https://issues.apache.org/jira/browse/VFS)
++ [Contributor License Agreement][cla]
++ [General GitHub documentation](http://help.github.com/)
++ [GitHub pull request documentation](http://help.github.com/send-pull-requests/)
++ [Apache Commons Twitter Account](https://twitter.com/ApacheCommons)
++ #apachecommons IRC channel on freenode.org
+
+[cla]:http://www.apache.org/licenses/#clas
diff --git a/trunk/LICENSE.txt b/trunk/LICENSE.txt
new file mode 100644
index 0000000..d645695
--- /dev/null
+++ b/trunk/LICENSE.txt
@@ -0,0 +1,202 @@
+
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/trunk/NOTICE.txt b/trunk/NOTICE.txt
new file mode 100644
index 0000000..b49f10e
--- /dev/null
+++ b/trunk/NOTICE.txt
@@ -0,0 +1,5 @@
+Apache Commons VFS
+Copyright 2002-2016 The Apache Software Foundation
+
+This product includes software developed at
+The Apache Software Foundation (http://www.apache.org/).
diff --git a/trunk/README.md b/trunk/README.md
new file mode 100644
index 0000000..f74d6d5
--- /dev/null
+++ b/trunk/README.md
@@ -0,0 +1,98 @@
+<!---
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<!---
+ +======================================================================+
+ |**** ****|
+ |**** THIS FILE IS GENERATED BY THE COMMONS BUILD PLUGIN ****|
+ |**** DO NOT EDIT DIRECTLY ****|
+ |**** ****|
+ +======================================================================+
+ | TEMPLATE FILE: readme-md-template.md |
+ | commons-build-plugin/trunk/src/main/resources/commons-xdoc-templates |
+ +======================================================================+
+ | |
+ | 1) Re-generate using: mvn commons:readme-md |
+ | |
+ | 2) Set the following properties in the component's pom: |
+ | - commons.componentid (required, alphabetic, lower case) |
+ | - commons.release.version (required) |
+ | |
+ | 3) Example Properties |
+ | |
+ | <properties> |
+ | <commons.componentid>math</commons.componentid> |
+ | <commons.release.version>1.2</commons.release.version> |
+ | </properties> |
+ | |
+ +======================================================================+
+--->
+Apache Commons VFS
+===================
+
+Apache Commons VFS is a Virtual File System library.
+
+Documentation
+-------------
+
+More information can be found on the [homepage](http://commons.apache.org/proper/commons-vfs).
+The [JavaDoc](http://commons.apache.org/proper/commons-vfs/apidocs/index.html) can be browsed.
+Questions related to the usage of Apache Commons VFS should be posted to the [user mailing list][ml].
+
+Where can I get the latest release?
+-----------------------------------
+You can download source and binaries from our [download page](http://commons.apache.org/proper/commons-vfs/download.html).
+
+Alternatively you can pull it from the central Maven repositories:
+
+```xml
+<dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2</artifactId>
+ <version>2.0</version>
+</dependency>
+```
+
+Contributing
+------------
+
+We accept PRs via github. The [developer mailing list][ml] is the main channel of communication for contributors.
+There are some guidelines which will make applying PRs easier for us:
++ No tabs! Please use spaces for indentation.
++ Respect the code style.
++ Create minimal diffs - disable on save actions like reformat source code or organize imports. If you feel the source code should be reformatted create a separate PR for this change.
++ Provide JUnit tests for your changes and make sure your changes don't break any existing tests by running ```mvn clean test```.
+
+If you plan to contribute on a regular basis, please consider filing a [contributor license agreement](http://www.apache.org/licenses/#clas).
+You can learn more about contributing via GitHub in our [contribution guidelines](https://github.com/apache/commons-vfs/blob/trunk/CONTRIBUTING.md).
+
+License
+-------
+Code is under the [Apache Licence v2](http://www.apache.org/licenses/LICENSE-2.0.txt).
+
+Donations
+---------
+You like Apache Commons VFS? Then [donate back to the ASF](http://www.apache.org/foundation/contributing.html) to support the development.
+
+Additional Resources
+--------------------
+
++ [Apache Commons Homepage](http://commons.apache.org/)
++ [Apache Bugtracker (JIRA)](https://issues.apache.org/jira/)
++ [Apache Commons Twitter Account](https://twitter.com/ApacheCommons)
++ #apachecommons IRC channel on freenode.org
+
+[ml]:http://commons.apache.org/proper/commons-vfs/mail-lists.html
diff --git a/trunk/README.txt b/trunk/README.txt
new file mode 100644
index 0000000..e3440cc
--- /dev/null
+++ b/trunk/README.txt
@@ -0,0 +1,9 @@
+To build Commons VFS run
+
+mvn clean install
+
+To build the distribution binaries run
+
+mvn -P apache-release clean install
+
+
diff --git a/trunk/RELEASE-NOTES.txt b/trunk/RELEASE-NOTES.txt
new file mode 100644
index 0000000..7ca2c70
--- /dev/null
+++ b/trunk/RELEASE-NOTES.txt
@@ -0,0 +1,198 @@
+ Apache Commons VFS 2.1
+ RELEASE NOTES
+
+The Apache Commons VFS team is pleased to announce the release of Apache Commons VFS 2.1
+
+Apache Commons VFS is a Virtual File System library.
+
+New features and bug fix release.
+
+Changes in this version include:
+
+New features:
+o VFS-198: [http] Make user agent configurable. Thanks to Andrew Franklin, Simon Legner.
+o VFS-555: [hdfs] Add the ability to specify an HDFS configuration file with HdfsFileSystemConfigBuilder.
+o [example] make VFS Shell print version and implement new 'info' command.
+o VFS-532: [FTP] Allow configuring remoteVerificationEnabled on FTPClient instances. Thanks to Gareth Daniel Smith.
+o VFS-468: [FTPS] Add option for KeyManager (and TrustManager) to support FTPS servers that ask for the client certificate for authentication.
+o VFS-412: [FTPS] Add support for command to set the DataChannelProtectionLevel. Thanks to Jose Juan Montiel.
+o VFS-442: [HDFS] Add an HDFS FileSystem Provider. Thanks to Dave Marion.
+o VFS-447: [FTP/FTPS] Update Apache Commons Net to 3.2 from 3.1.
+o VFS-445: Add FileSystemManager.resolveFile(URI) and resolveFile(URL).
+o VFS-440: [SFTP] Stream (e.g. netcat) proxy for Sftp file system (aka ProxyCommand). Thanks to bpiwowar.
+o VFS-432: [HTTP][WebDAV] Allow HTTP follow redirect.
+o VFS-431: FileSystemOption does not implement toString().
+o VFS-405: Get/set the file permissions. Thanks to dwaszak.
+o VFS-426: HTTP URL query string not part of cache key. Thanks to daniel.bergholm.
+o VFS-425: Add API FileObject.isExecutable().
+o VFS-421: [SFTP] Configure a custom Identity Repository. Thanks to bpiwowar.
+o VFS-417: [RAM][Local] Add and implement new API: RandomAccessContent.setLength(long).
+o VFS-400: Add a FileSelector based on regular expressions.
+o VFS-254: Let FileObject and FileContent extend java.io.Closeable. Thanks to mzawirski.
+o VFS-252: [SMB] SmbFileObject does not support setLastModifiedTime while jcifs supports it.
+o VFS-313: [FTP] Configuration does not include option for setting socket timeout. Thanks to bdavis@saintandreas.org.
+o VFS-414: [FTP] Add config API to set the file type.
+o VFS-182: [FTP] Usage of FTP with heterogeneous FTP server (possibility of using Ascii file type).
+o VFS-381: Iterate over a FileObject using the Java "foreach" statement, to provide all descendents of a FileObject.
+o VFS-373: Add FileContent write APIs.
+o VFS-372: Add constructors FileDepthSelector() and FileDepthSelector(int).
+o VFS-371: Add FileObject API deleteAll().
+o VFS-370: Add a FileExtensionSelector class.
+o VFS-367: Add APIs FileObject isFile(), FileObject isFolder(), and FileName isFile().
+
+Fixed Bugs:
+o VFS-424: Fix StandardFileSystemManager class loading so it works in a OSGi environment.
+o VFS-490: [vfsclassloader] Do not open folders with .jar extension. Adds tests.
+o VFS-582: [tests] revert rename of getTestDirectoryFile to make test classes more compatible for external providers.
+o VFS-480: Make startup of SoftRefsFileCache cleaner thread work and less racy to avoid leaks.
+o VFS-549: Use File.seperator instead of getProperty("file.separator").
+o VFS-567: [ftp] Ignore exceptions while QUIT/disconnect. Thanks to Antonio Petrelli.
+o VFS-572: [sftp] better documentation for knownhosts file option. Thanks to Sandra Parsick.
+o VFS-574: Ensure FileOpertionProviders are closed. Adds some testcases.
+ The error code for missing operations exceptions corrected: vfs.operation/operation-not-supported.error
+o VFS-279: [local] Avoid ClassCastException when replicating local files while OnCall caching is active. Thanks to Didier Earith, Simon Legner.
+o VFS-297: [sftp] VSF fails to reuse FileSystem instances if FileSystemOptions contain
+ an array as value. Reported for SFTP using identities. Thanks to Kirill Safonov, Jimmy Praet.
+o VFS-202: [http] Allow URLs responding with 405 to HEAD requests. Thanks to Sergey Vladimirov, Simon Legner.
+o VFS-490: [hdfs] Make OSGi package imports for hdfs resolution=optional.
+ Removed all scopes from dependency management.
+o VFS-560: [http] avoid initial HEAD request to root of HttpFileSystem as it might be wrong context.
+o VFS-236: [smb] Allow SMB to be used with no authentication. Thanks to Matt Casters.
+o VFS-564: Make some loggers static. Thanks to Dmitry Konstantinov.
+o VFS-557: [webdav][test] Create WebDav test directory in target/test. Avoid creating core/jackrabbit/tmp.
+ Logfiles of Jackrabbit are preserved when -DWebdavProviderTestCase.Debug=true is specified.
+o VFS-558: Make moveTo() and getParent() work with CacheStrategy.ON_CALL.
+ In case of FTP Provider it would lead otherwise to an UnsupportedOperationException.
+o [sandbox] RACRandomAccessFile is now in org.apache.commons.vfs2.util package (so sandbox has only one overlapping package).
+o VFS-552: [sandbox] include vfs-providers.xml in JAR for dynamic registration of mime and smb providers.
+o VFS-551: Javadoc: make it clear that DefaultCryptor is only an obfuscation function. Thanks to David Camilo Espitia Manrique.
+o VFS-309: DefaultFileContent will remove thread data whenever possible to avoid leaks.
+o VFS-487: DefaultFileMonitor detects recreated files. Thanks to Dave Marion.
+o VFS-523: [HDFS] Make HdfsFileObject.equal use system hashcode/equals instead of
+ wrongly comparing file path only. Thanks to Roger Whitcomb.
+o VFS-544: [Virtual] Allow virtual file systems and virtual file system provider
+ to be closed, to avoid memory leak.
+o VFS-142: Use ThreadLocal.remove() to clean out FileContentThreadData objects. Thanks to Ryan Boettcher.
+o VFS-545: Make DefaultFilesCache remove reference to filesystem when it is cleared (closed).
+o VFS-521: [Ram][Tests] Make RAM provider test pass on Java 8
+ (JDK-8042377, self-suppression not permitted, MonitorOutputStream#close()).
+o VFS-338: [Local][Tests] Avoid IndexOutOfBoundsException when validating local file URIs. Thanks to Daniel R..
+o VFS-489: [tests] ProviderWriteTests#testListener does not fail cleanly. Thanks to Bernd Eckenfels.
+o VFS-486: DefaultFileMonitor sleeps for twice the specified delay when checkPerRun > 0. Thanks to Sam Haldane.
+o VFS-482: Wrong assertion messages in RAM provider test case.
+o VFS-460: Dependency to commons-compress set as optional.
+o VFS-464: StaticUserAuthenticator should return only requested authentication data.
+o VFS-461: [FTP/FTPS] ConfigBuilder does not consider system properties for the value of SoTimeout and Encoding.
+o VFS-458: [FTPS] Provider missed functionality and bug fixes already available for the FTP provider.
+o VFS-452: [HTTP] HttpFileObject read/write attributes should reflect underlying FileSystem capabilities. Thanks to Jean-Marc Borer.
+o VFS-285: AbstractFileObject.getChildren() may corrupt its internal state if a filename
+ can not be resolved. Thanks to Kirill Safonov.
+o VFS-450: [HDFS] HDFSFileSystem.resolveFile() does not honor CacheStrategy.ON_RESOLVE. Thanks to Dave Marion.
+o VFS-448: commons-vfs 2.0 JAR has flawed OSGi MANIFEST.MF.
+o VFS-439: StaticUserAuthenticator usage example wrong. Thanks to pensecit.
+o VFS-437: [FTP] StackOverFlowError getting the type of a directory with a symbolic link to a parent directory with the same name. Thanks to denniszhu, danttran, jpowang.
+o VFS-435: FileSystemConfigBuilder does not use prefix for some system property lookups. Thanks to george scott.
+o VFS-434: FileSystemException should reuse IOException's chained exception.
+o VFS-433: [WebDAV] Message "vfs.provider.webdav/propfind.error" is not defined.
+o VFS-430: The SoftRefFilesCache class logs clear text password. Thanks to antonin.stefanutti.
+o VFS-429: Remove extra FileSystem ivar in AbstractFileObject subclasses with generics.
+o VFS-427: [HTTP] NPE on HttpFileObject.getContent().getContentInfo(). Thanks to awelynant.
+o VFS-406: [RAM] resize throws ArrayOOBE when shrinking in size. Thanks to mp1.
+o VFS-353: [FTP] Client should call logout before disconnecting. Thanks to bergander.
+o VFS-408: CompressedFileFileObject Exception thrown when container file has no extension. Thanks to anilm2@yahoo.com.
+o VFS-258: [SFTP][RAM] Unsafe casting to AbstractFileObject subclasses in doRename(). Thanks to mzawirski.
+o VFS-413: [FTP] No support for FTP servers with non Latin-1 control encoding. Thanks to polivenok.
+o VFS-200: [SFTP] Failure when files are very large.
+o VFS-296: [FTP] FTP socket timeout setting doesn't work if connect hangs. Thanks to andreasp.
+o VFS-410: [SFTP] SftpFileObject getInputStream(long) reads the whole file into memory. Thanks to mstockhammer.
+o VFS-407: [RAM] Reading a RAM FileSystem file fails because it never returns EOF -1. Thanks to mp1.
+o VFS-382: SFTP getChildren() does not fail when called on a file.
+o VFS-380: FTP connect.error message used instead of SFTP connect.error message.
+o VFS-378: Tar error message are missing from resource file.
+o VFS-374: Incorrect lazy initialization of static field org.apache.commons.vfs2.util.Messages.resources in org.apache.commons.vfs2.util.Messages.findMessage(String)Add FileContent write APIs.
+o VFS-355: The read method of RamFileRandomAccessContent's input stream does not return -1 at eof. Thanks to Miroslav Pokorny.
+o VFS-356: Throw an IOException if an attempt is made to seek to a position before the start of the file.
+o VFS-359: Don't delete a RamFileObject if it is open. Thanks to Miroslav Pokorny.
+o VFS-352: ZipFileSystem now uses an internal Map as a cache for all the files in the zip archive.
+o VFS-351: Chain the SftpException in the FileSystemException. Thanks to John Backstrand.
+o VFS-325: Allow # character in file names. Thanks to Larry Reeve.
+o VFS-335: Use atomic variables in MonitorInputStream.
+o VFS-364: Check the href in the response for just a path in addition to a full uri.
+
+Changes:
+o VFS-530: [hdfs] Use stable Apache Hadoop 2.6 dependencies. Thanks to Dave Marion.
+o VFS-601: Update Apache Commons Net from 3.3 to 3.4.
+o VFS-602: Update Apache Commons IO from 2.4 to 2.5.
+o VFS-579: Update Jsch from 0.1.51 to 0.1.53.
+o VFS-542: Update Jsch from 0.1.50 to 0.1.51.
+o VFS-578: Update Apache Commons Compress from 1.9 to 1.10.
+o VFS-541: Update Apache Commons Compress from 1.6 to 1.9.
+o VFS-540: Update Apache Commons Logging from 1.1.3 to 1.2.
+o VFS-539: Update Apache Commons Lang from 3.1 to 3.3.2.
+o VFS-526: [HDFS][Tests] Support HDFS testing on Windows (but keep profile "no-hdfs" enabled on Windows VFS-529).
+o VFS-453: [HTTP][WEBDAV] Add file system options for connect and socket timeout. Thanks to Jiri Syrovy.
+o VFS-167: [FTP] Allow Proxy support to file system options. Thanks to Jimmy Praet.
+o VFS-520: Make JavaDoc compatible with Java 8 tool.
+o VFS-518: Documentation of FileSystemOptions should be more helpful. Thanks to Roland Illig.
+o VFS-500: VFSClassLoader.findResources missing. Thanks to Bernd Eckenfels.
+o VFS-514: [tests] PermissionsTests leaves unclean test directory. Thanks to Bernd Eckenfels.
+o VFS-501: Hide passwords from log/console output. Thanks to Yves Schumann.
+o VFS-496: Resource translation issues. Thanks to Bernd Eckenfels.
+o VFS-494: [SFTP] No support for SFTP servers with non Latin-1 file name encoding. Thanks to Allen Xudong Cheng.
+o VFS-368: [SFTP] Documentation implies that "userDirIsRoot" defaults to true. Thanks to Brendan Long.
+o VFS-265: [FTP] Set user dir as root dir by default. Thanks to Scott Bjerstedt.
+o VFS-484: [SFTP] Update Jsch to 0.1.50 from 0.1.49.
+o VFS-507: Update to Apache Commons Collection 4.1 from 3.2.1 and use generics.
+o VFS-476: Update Apache Commons Logging to 1.1.3 from 1.1.2.
+o VFS-475: Update Apache Commons Net to 3.3 from 3.2.
+o VFS-506: [Tar][Bzip2] Update Apache Commons Compress to 1.6 from 1.5.
+o VFS-471: Update to Apache Commons Compress 1.5.
+o VFS-283: [SFTP] SFTP provider did not support passphrase-protected keys nor the exchange of a public key with
+ a requesting SFTP server. To support such triples (private key/passphrase/public key) instead of private
+ keys only, a new structure EntityInfo has been created. SftpFileSystemConfigBuilder has now the new
+ getter and setter methods getIdentityInfo and setIdentity info which replace the now deprecated methods
+ getIdentities and setIdentities.
+o VFS-463: FileSytemConfigBuilder supports system properties for the value of enum-based configuration entries.
+o VFS-462: [FTPS] Deprecate FtpsFileSystemConfigBuilder.setFtpsType and FtpsFileSystemConfigBuilder.getFtpsType
+ in favor of FtpsFileSystemConfigBuilder.setFtpsMode and FtpsFileSystemConfigBuilder.getFtpsMode which
+ use new enum FtpsMode instead.
+o VFS-459: [FTP/FTPS] Sent commands and the received answer is logged at debug level.
+o VFS-457: Update test dependencies: sshd-core version 0.7.0 to 0.8.0; mina-core 2.0.4 to 2.0.7; junit 4.11 to 4.12; slf4j-* 1.5.5 to 1.5.11
+o VFS-456: Use org.bouncycastel:bcprov-jdk16 instead of org.bouncycastle:bcprof-jdk15on since Java 1.6 is required.
+o VFS-415: Update VFS requirement to Java 1.6.
+o VFS-418: Update to Apache Commons Compress 1.4.1.
+o VFS-321: AbstractFileObject sometimes uses getFileSystem() and sometimes references "fs" field directly. Thanks to sebb.
+o VFS-327: UriParser.canonicalizePath possible NPE for filenameParser. Thanks to sebb.
+o VFS-416: [SFTP] Update Jsch to version 0.1.49 from 0.1.47.
+o VFS-395: [POM] Remove maven-scm-* dependencies.
+o VFS-411: [SFTP] Update Jsch to version 0.1.47 from 0.1.46.
+o VFS-409: Update Apache Commons Compress to 1.4 from 1.3.
+o VFS-404: [FTP][FTPS] Update Apache Commons Net to 3.1 from 3.0.1.
+o VFS-402: [WebDAV] Update Apache Jackrabbit 1.5.2 to 1.6.5.
+o VFS-401: Update JSch to 0.1.46 from 0.1.45 for the SFTP provider.
+o VFS-392: Build tests WebDAV file system with an embedded WebDAV server (Apache Jackrabbit).
+o VFS-391: Build tests URL HTTP file system with an embedded HTTP server (Apache HttpComponent Core).
+o VFS-390: Use variable argument list in org.apache.commons.vfs2.util.Messages instead of Object[].
+o VFS-389: Use variable argument lists in FileSystemException instead of Object[]s.
+o VFS-388: Build tests SFTP file system with an embedded SFTP server (Apache MINA).
+o VFS-387: Build tests FTP file system with an embedded FTP server (Apache MINA).
+o VFS-386: Build tests HTTP file system with an embedded HTTP server (Apache HttpComponent Core).
+o VFS-385: Add HTTP status code to HTTP file provider exception messages when available.
+o VFS-384: Update Apache Commons Net to 3.0.1 from 2.2 for FTP and SFTP providers.
+o VFS-383: Update JSch to 0.1.45 from 0.1.42 for the SFTP provider.
+o VFS-379: Replace custom BZIP2 code with Apache Commons Compress 1.3.
+o VFS-377: Replace custom TAR code with Apache Commons Compress 1.3.
+o VFS-375: Upgrade to Apache Commons Compress 1.3 from 1.2.
+o VFS-366: Can't sort a List of FileObject's, FileObject to implement Comparable<FileObject>.
+o VFS-341: Enable logging of JSch using the Commons Logging Log object in SftpClientFactory. Thanks to Rajika Kumarasiri.
+o VFS-361: Upgrade commons collections version to 3.2.1.
+
+Removed:
+o VFS-469: Remove unused dependency to javax.jcr:jcr.
+
+Historical list of changes: http://commons.apache.org/proper/commons-vfs/changes-report.html
+
+For complete information on Apache Commons VFS, including instructions on how to submit bug reports,
+patches, or suggestions for improvement, see the Apache Apache Commons VFS website:
+
+http://commons.apache.org/proper/commons-vfs/
diff --git a/trunk/checkstyle-suppressions.xml b/trunk/checkstyle-suppressions.xml
new file mode 100644
index 0000000..b44b9d8
--- /dev/null
+++ b/trunk/checkstyle-suppressions.xml
@@ -0,0 +1,39 @@
+<?xml version="1.0"?>
+
+<!DOCTYPE suppressions PUBLIC
+ "-//Puppy Crawl//DTD Suppressions 1.0//EN"
+ "http://www.puppycrawl.com/dtds/suppressions_1_0.dtd">
+
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<!-- Exceptions for Checkstyle -->
+
+<suppressions>
+
+ <!-- Disable the warnings for the generated classes -->
+ <suppress checks=".*" files="ParseException.java"/>
+ <suppress checks=".*" files="PropertyListParser.java"/>
+ <suppress checks=".*" files="PropertyListParserConstants.java"/>
+ <suppress checks=".*" files="PropertyListParserTokenManager.java"/>
+ <suppress checks=".*" files="SimpleCharStream.java"/>
+ <suppress checks=".*" files="Token.java"/>
+ <suppress checks=".*" files="TokenMgrError.java"/>
+
+ <suppress checks="MissingSwitchDefault" files="PropertiesConfiguration.java"/>
+
+</suppressions>
diff --git a/trunk/checkstyle.properties b/trunk/checkstyle.properties
new file mode 100644
index 0000000..27906bf
--- /dev/null
+++ b/trunk/checkstyle.properties
@@ -0,0 +1,24 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+checkstyle.maxlinelen = 120
+checkstyle.lcurly.type = nl
+checkstyle.lcurly.method = nl
+checkstyle.lcurly.other = nl
+checkstyle.rcurly = alone
+checkstyle.paren.pad = ignore
+checkstyle.ignore.whitespace.cast = true
+checkstyle.javadoc.scope = package
+checkstyle.require.packagehtml = true
diff --git a/trunk/checkstyle.xml b/trunk/checkstyle.xml
new file mode 100644
index 0000000..966243b
--- /dev/null
+++ b/trunk/checkstyle.xml
@@ -0,0 +1,213 @@
+<?xml version="1.0"?>
+<!DOCTYPE module PUBLIC
+ "-//Puppy Crawl//DTD Check Configuration 1.1//EN"
+ "http://www.puppycrawl.com/dtds/configuration_1_1.dtd">
+
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<!-- Checkstyle configuration that checks the commons-configuration coding conventions -->
+
+<module name="Checker">
+ <property name="localeLanguage" value="en"/>
+
+ <!-- Checks that a package.html file exists for each package. -->
+ <!-- See http://checkstyle.sourceforge.net/config_javadoc.html -->
+ <module name="JavadocPackage">
+ <property name="allowLegacy" value="true"/>
+ </module>
+
+ <!-- Checks whether files end with a new line. -->
+ <!-- See http://checkstyle.sf.net/config_misc.html#NewlineAtEndOfFile -->
+ <module name="NewlineAtEndOfFile"/>
+
+ <!-- Checks that property files contain the same keys. -->
+ <!-- See http://checkstyle.sf.net/config_misc.html#Translation -->
+ <module name="Translation"/>
+
+ <!-- Checks for Tab characters -->
+ <!-- See http://checkstyle.sourceforge.net/config_whitespace.html#FileTabCharacter -->
+ <module name="FileTabCharacter">
+ <property name="fileExtensions" value="java"/>
+ </module>
+
+ <!-- Checks for white space at the end of the line -->
+ <!-- See http://checkstyle.sourceforge.net/config_regexp.html -->
+ <module name="RegexpSingleline">
+ <property name="format" value="\s+$"/>
+ <property name="message" value="Line has trailing spaces."/>
+ <property name="fileExtensions" value="java"/>
+ </module>
+
+ <!-- @author tags are deprecated -->
+ <module name="RegexpSingleline">
+ <property name="format" value="^\s+\*\s+@author\s"/>
+ <property name="message" value="Deprecated @author tag"/>
+ <property name="fileExtensions" value="java"/>
+ <property name="severity" value="warning"/>
+ </module>
+
+ <!-- Don't use SVN $Date$ variable - it's localized and causes source archives to differ from the SVN tag -->
+ <module name="RegexpSingleline">
+ <property name="format" value="\$Date.+\$"/>
+ <property name="message" value="Don't use SVN $Date$ variable"/>
+ <property name="fileExtensions" value="java"/>
+ <property name="severity" value="warning"/>
+ </module>
+
+ <!-- Exceptions -->
+ <!--<module name="SuppressionFilter">
+ <property name="file" value="conf/checkstyle-suppressions.xml"/>
+ </module> -->
+
+ <module name="TreeWalker">
+
+ <property name="cacheFile" value="${checkstyle.cache.file}"/>
+
+ <!-- Checks for Javadoc comments. -->
+ <!-- See http://checkstyle.sf.net/config_javadoc.html -->
+ <module name="JavadocMethod">
+ <property name="scope" value="public"/>
+ <property name="allowUndeclaredRTE" value="true"/>
+ <property name="allowMissingJavadoc" value="true"/>
+ </module>
+ <!-- http://checkstyle.sourceforge.net/config_javadoc.html#JavadocType -->
+ <module name="JavadocType">
+ <!-- It is unfortunate to have to do this but checkstyle doesn't allow custom tags -->
+ <property name="allowUnknownTags" value="true"/>
+ </module>
+ <module name="JavadocVariable">
+ <property name="scope" value="protected"/>
+ </module>
+ <module name="JavadocStyle">
+ <property name="scope" value="public"/>
+ </module>
+
+ <!-- Checks for Naming Conventions. -->
+ <!-- See http://checkstyle.sf.net/config_naming.html -->
+ <module name="ConstantName">
+ <property name="format" value="^[A-Z][A-Z0-9]*(_[A-Z0-9]+)*$|^capabilities$|^log$"/>
+ </module>
+ <module name="LocalFinalVariableName"/>
+ <module name="LocalVariableName"/>
+ <module name="MemberName"/>
+ <module name="MethodName"/>
+ <module name="PackageName"/>
+ <module name="ParameterName"/>
+ <module name="StaticVariableName"/>
+ <module name="TypeName"/>
+
+ <!-- Following interprets the header file as regular expressions. -->
+ <!-- <module name="RegexpHeader"/> -->
+
+ <!-- Checks for imports -->
+ <!-- See http://checkstyle.sf.net/config_import.html -->
+ <module name="AvoidStarImport"/>
+ <module name="IllegalImport"/> <!-- defaults to sun.* packages -->
+ <module name="RedundantImport"/>
+ <module name="UnusedImports"/>
+
+ <!-- Checks for Size Violations. -->
+ <!-- See http://checkstyle.sf.net/config_sizes.html -->
+ <!--<module name="FileLength"/>-->
+ <module name="LineLength">
+ <property name="max" value="120"/>
+ </module>
+ <module name="MethodLength"/>
+ <module name="ParameterNumber">
+ <property name="max" value="10"/>
+ </module>
+
+ <!-- Checks for whitespace -->
+ <!-- See http://checkstyle.sf.net/config_whitespace.html -->
+ <module name="EmptyForIteratorPad"/>
+ <module name="NoWhitespaceAfter"/>
+ <module name="NoWhitespaceBefore"/>
+ <module name="OperatorWrap">
+ <property name="tokens" value="ASSIGN"/>
+ <property name="option" value="eol"/>
+ </module>
+ <module name="ParenPad"/>
+ <module name="WhitespaceAfter"/>
+ <module name="WhitespaceAround"/>
+ <module name="GenericWhitespace"/>
+
+ <!-- Modifier Checks -->
+ <!-- See http://checkstyle.sf.net/config_modifiers.html -->
+ <module name="ModifierOrder"/>
+ <module name="RedundantModifier"/>
+
+ <!-- Checks for blocks. You know, those {}'s -->
+ <!-- See http://checkstyle.sf.net/config_blocks.html -->
+ <module name="AvoidNestedBlocks"/>
+ <!-- Require empty catch blocks to have at least a comment -->
+ <module name="EmptyBlock">
+ <property name="option" value="text"/>
+ <property name="tokens" value="LITERAL_CATCH"/>
+ </module>
+ <module name="LeftCurly">
+ <property name="option" value="nl"/>
+ </module>
+ <module name="NeedBraces"/>
+ <module name="RightCurly">
+ <property name="option" value="alone"/>
+ </module>
+
+ <!-- Checks for common coding problems -->
+ <!-- See http://checkstyle.sf.net/config_coding.html -->
+ <module name="CovariantEquals"/>
+ <module name="EqualsHashCode"/>
+ <module name="IllegalInstantiation"/>
+ <!-- <module name="InnerAssignment"/> -->
+ <module name="MagicNumber">
+ <property name="ignoreNumbers" value="-1,0,1,2,3"/>
+ </module>
+ <module name="RedundantThrows">
+ <property name="allowUnchecked" value="true"/>
+ </module>
+ <module name="SimplifyBooleanExpression"/>
+ <module name="SimplifyBooleanReturn"/>
+ <module name="StringLiteralEquality"/>
+ <module name="SuperClone"/>
+ <module name="SuperFinalize"/>
+ <module name="DeclarationOrder"/>
+ <!-- <module name="ExplicitInitialization"/> -->
+ <module name="DefaultComesLast"/>
+ <module name="FallThrough"/>
+ <module name="MultipleVariableDeclarations"/>
+ <!-- <module name="UnnecessaryParentheses"/> -->
+
+ <!-- Checks for class design -->
+ <!-- See http://checkstyle.sf.net/config_design.html -->
+ <module name="FinalClass"/>
+ <module name="HideUtilityClassConstructor"/>
+ <module name="InterfaceIsType"/>
+ <module name="VisibilityModifier">
+ <property name="protectedAllowed" value="true"/>
+ </module>
+
+ <!-- Miscellaneous other checks. -->
+ <!-- See http://checkstyle.sf.net/config_misc.html -->
+ <module name="ArrayTypeStyle"/>
+ <module name="TodoComment">
+ <property name="severity" value="info"/>
+ </module>
+ <module name="UpperEll"/>
+
+ </module>
+
+</module>
diff --git a/trunk/core/pom.xml b/trunk/core/pom.xml
new file mode 100644
index 0000000..a1c1cf5
--- /dev/null
+++ b/trunk/core/pom.xml
@@ -0,0 +1,359 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+
+ <name>Apache Commons VFS Core</name>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2</artifactId>
+ <version>2.1</version>
+ <description>Apache Commons VFS is a Virtual File System library.</description>
+ <url>http://commons.apache.org/proper/commons-vfs/</url>
+
+ <parent>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2-project</artifactId>
+ <version>2.1</version>
+ <relativePath>../</relativePath>
+ </parent>
+
+ <dependencies>
+ <dependency>
+ <groupId>commons-logging</groupId>
+ <artifactId>commons-logging</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>ant</groupId>
+ <artifactId>ant</artifactId>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>commons-net</groupId>
+ <artifactId>commons-net</artifactId>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-compress</artifactId>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-collections4</artifactId>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-common</artifactId>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-hdfs</artifactId>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>commons-httpclient</groupId>
+ <artifactId>commons-httpclient</artifactId>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.jackrabbit</groupId>
+ <artifactId>jackrabbit-webdav</artifactId>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>com.jcraft</groupId>
+ <artifactId>jsch</artifactId>
+ <optional>true</optional>
+ </dependency>
+
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <!-- Test FTP with Apache FTP Server (MINA) -->
+ <dependency>
+ <groupId>org.apache.ftpserver</groupId>
+ <artifactId>ftpserver-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <!-- Test SFTP with Apache SHHd Server (MINA) -->
+ <dependency>
+ <groupId>org.apache.sshd</groupId>
+ <artifactId>sshd-core</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.bouncycastle</groupId>
+ <artifactId>bcprov-jdk16</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <!-- Test HTTP with Apache HttpComponent Core -->
+ <dependency>
+ <groupId>org.apache.httpcomponents</groupId>
+ <artifactId>httpcore-nio</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <!-- Test WebDAV with Apache Jackrabbit-->
+ <dependency>
+ <groupId>org.apache.jackrabbit</groupId>
+ <artifactId>jackrabbit-standalone</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <!-- Test HDFS with Apache Hadoop -->
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-common</artifactId>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-hdfs</artifactId>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>javax.ws.rs</groupId>
+ <artifactId>jsr311-api</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <properties>
+ <vfs.parent.dir>${basedir}/..</vfs.parent.dir>
+ </properties>
+
+ <build>
+ <resources>
+ <resource>
+ <directory>src/main/java</directory>
+ <excludes>
+ <exclude>**/*.html</exclude>
+ <exclude>**/*.java</exclude>
+ </excludes>
+ </resource>
+ <!-- include NOTICE/LICENSE in generated jar -->
+ <resource>
+ <directory>${vfs.parent.dir}</directory>
+ <targetPath>META-INF</targetPath>
+ <includes>
+ <include>NOTICE.txt</include>
+ <include>LICENSE.txt</include>
+ </includes>
+ </resource>
+ </resources>
+
+
+ <testResources>
+ <testResource>
+ <directory>src/test/resources</directory>
+ </testResource>
+ <!-- include NOTICE/LICENSE in generated test jar -->
+ <testResource>
+ <directory>${vfs.parent.dir}</directory>
+ <targetPath>META-INF</targetPath>
+ <includes>
+ <include>NOTICE.txt</include>
+ <include>LICENSE.txt</include>
+ </includes>
+ </testResource>
+ </testResources>
+
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <executions>
+ <execution>
+ <goals>
+ <goal>test-jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-antrun-plugin</artifactId>
+ <executions>
+ <execution>
+ <phase>process-test-classes</phase>
+ <configuration>
+ <target>
+ <move todir="${project.build.testOutputDirectory}/test-data/code" failonerror="false">
+ <fileset dir="${project.build.testOutputDirectory}/code" />
+ </move>
+ </target>
+ </configuration>
+ <goals>
+ <goal>run</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <trimStackTrace>false</trimStackTrace>
+ <systemPropertyVariables>
+ <test.basedir>target/test-classes/test-data</test.basedir>
+ <test.basedir.res>test-data</test.basedir.res>
+ <derby.stream.error.file>target/derby.log</derby.stream.error.file>
+ </systemPropertyVariables>
+ <excludes>
+ <!-- Main class -->
+ <exclude>**/RunTest.java</exclude>
+ <!-- inner classes -->
+ <exclude>**/*$*</exclude>
+ </excludes>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+ <profiles>
+ <profile>
+ <id>webdav</id>
+ <activation>
+ <activeByDefault>false</activeByDefault>
+ </activation>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <systemPropertyVariables>
+ <test.webdav.uri>${test.webdav.uri}</test.webdav.uri>
+ </systemPropertyVariables>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+
+ <profile>
+ <id>ftp</id>
+ <activation>
+ <activeByDefault>false</activeByDefault>
+ </activation>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <systemPropertyVariables>
+ <test.ftp.uri>${test.ftp.uri}</test.ftp.uri>
+ </systemPropertyVariables>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+
+ <profile>
+ <id>sftp</id>
+ <activation>
+ <activeByDefault>false</activeByDefault>
+ </activation>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <systemPropertyVariables>
+ <test.sftp.uri>${test.sftp.uri}</test.sftp.uri>
+ </systemPropertyVariables>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+
+ <profile>
+ <id>http</id>
+ <activation>
+ <activeByDefault>false</activeByDefault>
+ </activation>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <systemPropertyVariables>
+ <test.http.uri>${test.http.uri}</test.http.uri>
+ </systemPropertyVariables>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+
+ <!-- On Windows we disable hdfs tests by default. -->
+ <profile>
+ <id>no-test-hdfs</id>
+ <activation>
+ <activeByDefault>false</activeByDefault>
+ <os>
+ <family>Windows</family>
+ </os>
+ </activation>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <excludes>
+ <exclude>**/HdfsFileProviderTest.java</exclude>
+ <exclude>**/HdfsFileProviderTestCase.java</exclude>
+ </excludes>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ </profiles>
+
+</project>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/AllFileSelector.java b/trunk/core/src/main/java/org/apache/commons/vfs2/AllFileSelector.java
new file mode 100644
index 0000000..9255618
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/AllFileSelector.java
@@ -0,0 +1,46 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+/**
+ * A {@link FileSelector} that selects everything.
+ */
+public class AllFileSelector
+ implements FileSelector
+{
+ /**
+ * Determines if a file or folder should be selected.
+ * @param fileInfo The file selection information.
+ * @return true if the file should be selected, false otherwise.
+ */
+ @Override
+ public boolean includeFile(final FileSelectInfo fileInfo)
+ {
+ return true;
+ }
+
+ /**
+ * Determines whether a folder should be traversed.
+ * @param fileInfo The file selection information.
+ * @return true if descendants should be traversed, false otherwise.
+ */
+ @Override
+ public boolean traverseDescendents(final FileSelectInfo fileInfo)
+ {
+ return true;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/CacheStrategy.java b/trunk/core/src/main/java/org/apache/commons/vfs2/CacheStrategy.java
new file mode 100644
index 0000000..c2785e5
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/CacheStrategy.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+/**
+ * An enumerated type to deal with the various cache strategies.
+ */
+public enum CacheStrategy
+{
+ /**
+ * Deal with cached data manually. Call {@link FileObject#refresh()} to refresh the object data.
+ */
+ MANUAL("manual"),
+
+ /**
+ * Refresh the data every time you request a file from {@link FileSystemManager#resolveFile}.
+ */
+ ON_RESOLVE("onresolve"),
+
+ /**
+ * Refresh the data every time you call a method on the fileObject.
+ * You'll use this only if you really need the latest info as this setting is a major performance
+ * loss.
+ */
+ ON_CALL("oncall");
+
+ /**
+ * Cache strategy name
+ */
+ private final String realName;
+
+ private CacheStrategy(final String name)
+ {
+ this.realName = name;
+ }
+
+ /**
+ * Returns the name of the scope.
+ * @return the name of the scope.
+ */
+ @Override
+ public String toString()
+ {
+ return realName;
+ }
+
+ /**
+ * Returns the name of the scope.
+ * @return the name of the scope.
+ */
+ public String getName()
+ {
+ return realName;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/Capability.java b/trunk/core/src/main/java/org/apache/commons/vfs2/Capability.java
new file mode 100644
index 0000000..8fe8474
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/Capability.java
@@ -0,0 +1,155 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+/**
+ * An enumerated type representing the capabilities of files and file systems.
+ */
+public enum Capability
+{
+ /**
+ * File content can be read.
+ */
+ READ_CONTENT,
+
+ /**
+ * File content can be written.
+ */
+ WRITE_CONTENT,
+
+ /**
+ * File content can be read in random mode.
+ */
+ RANDOM_ACCESS_READ,
+
+ /**
+ * File content length can be set in random mode.
+ */
+ RANDOM_ACCESS_SET_LENGTH,
+
+ /**
+ * File content can be written in random mode.
+ */
+ RANDOM_ACCESS_WRITE,
+
+ /**
+ * File content can be appended.
+ */
+ APPEND_CONTENT,
+
+ /**
+ * File attributes are supported.
+ */
+ ATTRIBUTES,
+
+ /**
+ * File last-modified time is supported.
+ */
+ LAST_MODIFIED,
+
+ /**
+ * File get last-modified time is supported.
+ */
+ GET_LAST_MODIFIED,
+
+ /**
+ * File set last-modified time is supported.
+ */
+ SET_LAST_MODIFIED_FILE,
+
+ /**
+ * folder set last-modified time is supported.
+ */
+ SET_LAST_MODIFIED_FOLDER,
+
+ /**
+ * File content signing is supported.
+ */
+ SIGNING,
+
+ /**
+ * Files can be created.
+ */
+ CREATE,
+
+ /**
+ * Files can be deleted.
+ */
+ DELETE,
+
+ /**
+ * Files can be renamed.
+ */
+ RENAME,
+
+ /**
+ * The file type can be determined.
+ */
+ GET_TYPE,
+
+ /**
+ * Children of files can be listed.
+ */
+ LIST_CHILDREN,
+
+ /**
+ * URI are supported. Files without this capability use URI that do not
+ * globally and uniquely identify the file.
+ */
+ URI,
+
+ /**
+ * File system attributes are supported.
+ */
+ FS_ATTRIBUTES,
+
+ /**
+ * Junctions are supported.
+ */
+ JUNCTIONS,
+
+ /**
+ * The set of attributes defined by the Jar manifest specification are
+ * supported. The attributes aren't necessarily stored in a manifest file.
+ */
+ MANIFEST_ATTRIBUTES,
+
+ /**
+ * The provider itself do not provide a filesystem. It simply resolves a full name
+ * and dispatches the request back to the filesystemmanager.<br>
+ * A provider with this capability cant tell much about the capabilities about the
+ * finally used filesystem in advance.
+ */
+ DISPATCHER,
+
+ /**
+ * A compressed filesystem is a filesystem which use compression.
+ */
+ COMPRESS,
+
+ /**
+ * A virtual filesystem can be an archive like tar or zip.
+ */
+ VIRTUAL,
+
+ /**
+ * Provides directories which allows you to read its content through
+ * {@link org.apache.commons.vfs2.FileContent#getInputStream()}.
+ * @since 2.0
+ */
+ DIRECTORY_READ_CONTENT;
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileChangeEvent.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileChangeEvent.java
new file mode 100644
index 0000000..74a72ab
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileChangeEvent.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+/**
+ * An event fired when a file is changed.
+ */
+public class FileChangeEvent
+{
+ /**
+ * The file object
+ */
+ private final FileObject file;
+
+ public FileChangeEvent(final FileObject file)
+ {
+ this.file = file;
+ }
+
+ /**
+ * Returns the file that changed.
+ * @return The FileObject that was changed.
+ */
+ public FileObject getFile()
+ {
+ return file;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileContent.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileContent.java
new file mode 100644
index 0000000..95ea8fc
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileContent.java
@@ -0,0 +1,293 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.security.cert.Certificate;
+import java.util.Map;
+
+import org.apache.commons.vfs2.util.RandomAccessMode;
+
+/**
+ * Represents the data content of a file.
+ * <p>
+ * To read from a file, use the {@code InputStream} returned by {@link #getInputStream()}.
+ * </p>
+ * <p>
+ * To write to a file, use the {@code OutputStream} returned by {@link #getOutputStream()} method. This will create
+ * the file, and the parent folder, if necessary.
+ * </p>
+ * <p>
+ * A file may have multiple InputStreams open at the same time.
+ * </p>
+ *
+ * @see FileObject#getContent
+ */
+public interface FileContent extends Closeable
+{
+ /**
+ * Returns the file which this is the content of.
+ * @return The FileObject this is the content of.
+ */
+ FileObject getFile();
+
+ /**
+ * Determines the size of the file, in bytes.
+ *
+ * @return The size of the file, in bytes.
+ * @throws FileSystemException If the file does not exist, or is being written to, or on error
+ * determining the size.
+ */
+ long getSize() throws FileSystemException;
+
+ /**
+ * Determines the last-modified timestamp of the file.
+ *
+ * @return The last-modified timestamp.
+ * @throws FileSystemException If the file does not exist, or is being written to, or on error
+ * determining the last-modified timestamp.
+ */
+ long getLastModifiedTime() throws FileSystemException;
+
+ /**
+ * Sets the last-modified timestamp of the file. Creates the file if
+ * it does not exist.
+ *
+ * @param modTime The time to set the last-modified timestamp to.
+ * @throws FileSystemException If the file is read-only, or is being written to, or on error
+ * setting the last-modified timestamp.
+ */
+ void setLastModifiedTime(long modTime) throws FileSystemException;
+
+ /**
+ * Checks if an attribute of the file's content exists.
+ *
+ * @param attrName The name of the attribute.
+ * @return true if the attribute exists, false otherwise.
+ * @throws FileSystemException If the file does not exist, or does not support
+ * attributes.
+ */
+ boolean hasAttribute(String attrName)
+ throws FileSystemException;
+
+ /**
+ * Returns a read-only map of this file's attributes.
+ * @return The attribute Map.
+ * @throws FileSystemException If the file does not exist, or does not support attributes.
+ */
+ Map<String, Object> getAttributes() throws FileSystemException;
+
+ /**
+ * Lists the attributes of the file's content.
+ *
+ * @return The names of the attributes. Never returns null;
+ * @throws FileSystemException If the file does not exist, or does not support attributes.
+ */
+ String[] getAttributeNames() throws FileSystemException;
+
+ /**
+ * Gets the value of an attribute of the file's content.
+ *
+ * @param attrName The name of the attribute. Attribute names are case insensitive.
+ * @return The value of the attribute, or null if the attribute value is
+ * unknown.
+ * @throws FileSystemException If the file does not exist, or does not support attributes.
+ */
+ Object getAttribute(String attrName) throws FileSystemException;
+
+ /**
+ * Sets the value of an attribute of the file's content. Creates the
+ * file if it does not exist.
+ *
+ * @param attrName The name of the attribute.
+ * @param value The value of the attribute.
+ * @throws FileSystemException If the file does not exist, or is read-only, or does not support
+ * attributes, or on error setting the attribute.
+ */
+ void setAttribute(String attrName, Object value)
+ throws FileSystemException;
+
+ /**
+ * Removes the value of an attribute of the file's content.
+ *
+ * @param attrName The name of the attribute.
+ * @throws FileSystemException If the file does not exist, or is read-only, or does not support
+ * attributes, or on error removing the attribute.
+ */
+ void removeAttribute(String attrName)
+ throws FileSystemException;
+
+ /**
+ * Retrieves the certificates if any used to sign this file or folder.
+ *
+ * @return The certificates, or an empty array if there are no certificates or
+ * the file does not support signing.
+ * @throws FileSystemException If the file does not exist, or is being written.
+ */
+ Certificate[] getCertificates() throws FileSystemException;
+
+ /**
+ * Returns an input stream for reading the file's content.
+ * <p>
+ * There may only be a single input or output stream open for the
+ * file at any time.
+ *
+ * @return An input stream to read the file's content from. The input
+ * stream is buffered, so there is no need to wrap it in a
+ * {@code BufferedInputStream}.
+ * @throws FileSystemException If the file does not exist, or is being read, or is being written,
+ * or on error opening the stream.
+ */
+ InputStream getInputStream() throws FileSystemException;
+
+ /**
+ * Returns an output stream for writing the file's content.
+ * <p>
+ * If the file does not exist, this method creates it, and the parent
+ * folder, if necessary. If the file does exist, it is replaced with
+ * whatever is written to the output stream.
+ * <p>
+ * There may only be a single input or output stream open for the
+ * file at any time.
+ *
+ * @return An output stream to write the file's content to. The stream is
+ * buffered, so there is no need to wrap it in a
+ * {@code BufferedOutputStream}.
+ * @throws FileSystemException If the file is read-only, or is being read, or is being written,
+ * or on error opening the stream.
+ */
+ OutputStream getOutputStream() throws FileSystemException;
+
+ /**
+ * Returns an stream for reading/writing the file's content.
+ * <p>
+ * If the file does not exist, and you use one of the write* methods,
+ * this method creates it, and the parent folder, if necessary.
+ * If the file does exist, parts of the file are replaced with whatever is written
+ * at a given position.
+ * <p>
+ * There may only be a single input or output stream open for the
+ * file at any time.
+ *
+ * @param mode The mode to use to access the file.
+ * @return the stream for reading and writing the file's content.
+ * @throws FileSystemException If the file is read-only, or is being read, or is being written,
+ * or on error opening the stream.
+ */
+ RandomAccessContent getRandomAccessContent(final RandomAccessMode mode) throws FileSystemException;
+
+ /**
+ * Returns an output stream for writing the file's content.
+ * <p>
+ * If the file does not exist, this method creates it, and the parent
+ * folder, if necessary. If the file does exist, it is replaced with
+ * whatever is written to the output stream.
+ * <p>
+ * There may only be a single input or output stream open for the
+ * file at any time.
+ *
+ * @param bAppend true if you would like to append to the file.
+ * This may not be supported by all implementations.
+ * @return An output stream to write the file's content to. The stream is
+ * buffered, so there is no need to wrap it in a
+ * {@code BufferedOutputStream}.
+ * @throws FileSystemException If the file is read-only, or is being read, or is being written,
+ * or bAppend is true and the implementation does not support it,
+ * or on error opening the stream.
+ */
+ OutputStream getOutputStream(boolean bAppend) throws FileSystemException;
+
+ /**
+ * Closes all resources used by the content, including any open stream.
+ * Commits pending changes to the file.
+ * <p>
+ * This method is a hint to the implementation that it can release
+ * resources. This object can continue to be used after calling this
+ * method.
+ *
+ * @throws FileSystemException if an error occurs closing the file.
+ */
+ @Override
+ void close() throws FileSystemException;
+
+ /**
+ * get the content info. e.g. type, encoding, ...
+ * @return the FileContentInfo
+ * @throws FileSystemException if an error occurs.
+ */
+ FileContentInfo getContentInfo() throws FileSystemException;
+
+ /**
+ * check if this file has open streams.
+ * @return true if the file is open, false otherwise.
+ */
+ boolean isOpen();
+
+ /**
+ * Writes this content to another FileContent.
+ *
+ * @param output
+ * The target OutputStream.
+ * @throws IOException
+ * if an error occurs writing the content.
+ * @return the total number of bytes written
+ * @since 2.1
+ */
+ long write(FileContent output) throws IOException;
+
+ /**
+ * Writes this content to another FileObject.
+ *
+ * @param file
+ * The target FileObject.
+ * @throws IOException
+ * if an error occurs writing the content.
+ * @return the total number of bytes written
+ * @since 2.1
+ */
+ long write(FileObject file) throws IOException;
+
+ /**
+ * Writes this content to an OutputStream.
+ *
+ * @param output
+ * The target OutputStream.
+ * @return the total number of bytes written
+ * @throws IOException
+ * if an error occurs writing the content.
+ * @since 2.1
+ */
+ long write(OutputStream output) throws IOException;
+
+ /**
+ * Writes this content to an OutputStream.
+ *
+ * @param output
+ * The target OutputStream.
+ * @param bufferSize
+ * The buffer size to write data chunks.
+ * @return the total number of bytes written
+ * @throws IOException
+ * if an error occurs writing the file.
+ * @since 2.1
+ */
+ long write(OutputStream output, int bufferSize) throws IOException;
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileContentInfo.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileContentInfo.java
new file mode 100644
index 0000000..052018d
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileContentInfo.java
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+/**
+ * Informs on the content of a file with content type and encoding.
+ */
+public interface FileContentInfo
+{
+ /**
+ * Gets the content encoding.
+ *
+ * @return The file content encoding.
+ */
+ String getContentEncoding();
+
+ /**
+ * Gets the content type.
+ *
+ * @return The file content type.
+ */
+ String getContentType();
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileContentInfoFactory.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileContentInfoFactory.java
new file mode 100644
index 0000000..689f203
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileContentInfoFactory.java
@@ -0,0 +1,34 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+/**
+ * Creates {@link FileContentInfo} instances to determine the content-info for given file contents.
+ */
+public interface FileContentInfoFactory
+{
+ /**
+ * Creates a FileContentInfo for a the given FileContent.
+ *
+ * @param fileContent
+ * Use this FileContent to create a matching FileContentInfo
+ * @return a FileContentInfo for the given FileContent.
+ * @throws FileSystemException
+ * when a problem occurs creating the FileContentInfo.
+ */
+ FileContentInfo create(FileContent fileContent) throws FileSystemException;
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileDepthSelector.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileDepthSelector.java
new file mode 100644
index 0000000..364f00d
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileDepthSelector.java
@@ -0,0 +1,96 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+/**
+ * A {@link FileSelector} that selects all files in a particular depth range.
+ */
+public class FileDepthSelector implements FileSelector
+{
+ /**
+ * The minimum depth
+ */
+ private final int minDepth;
+
+ /**
+ * The maximum depth
+ */
+ private final int maxDepth;
+
+ /**
+ * Creates a selector with the given minimum and maximum depths.
+ *
+ * @param minDepth
+ * minimum depth
+ * @param maxDepth
+ * maximum depth
+ */
+ public FileDepthSelector(final int minDepth, final int maxDepth)
+ {
+ this.minDepth = minDepth;
+ this.maxDepth = maxDepth;
+ }
+
+ /**
+ * Creates a selector with the same minimum and maximum depths.
+ *
+ * @param minMaxDepth
+ * minimum and maximum depth
+ * @since 2.1
+ */
+ public FileDepthSelector(final int minMaxDepth)
+ {
+ this(minMaxDepth, minMaxDepth);
+ }
+
+ /**
+ * Creates a selector with the same minimum and maximum depths of 0.
+ *
+ * @since 2.1
+ */
+ public FileDepthSelector()
+ {
+ this(0, 0);
+ }
+
+ /**
+ * Determines if a file or folder should be selected.
+ *
+ * @param fileInfo
+ * The file selection information
+ * @return true if the file or folder should be included, false otherwise.
+ */
+ @Override
+ public boolean includeFile(final FileSelectInfo fileInfo)
+ {
+ final int depth = fileInfo.getDepth();
+ return minDepth <= depth && depth <= maxDepth;
+ }
+
+ /**
+ * Determines whether a folder should be traversed.
+ *
+ * @param fileInfo
+ * The file selection information
+ * @return true if the file or folder should be traversed, false otherwise.
+ */
+ @Override
+ public boolean traverseDescendents(final FileSelectInfo fileInfo)
+ {
+ return fileInfo.getDepth() < maxDepth;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileExtensionSelector.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileExtensionSelector.java
new file mode 100644
index 0000000..e0a0e72
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileExtensionSelector.java
@@ -0,0 +1,108 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Set;
+
+/**
+ * A {@link FileSelector} that selects based on file extensions.
+ * <p>
+ * The extension comparison is case insensitive.
+ * </p>
+ * <p>
+ * The selector makes a copy of a given Collection or array. Changing the object passed in the constructors will not
+ * affect the selector.
+ * </p>
+ *
+ * @since 2.1
+ */
+public class FileExtensionSelector implements FileSelector
+{
+
+ /**
+ * The extensions to select.
+ */
+ private final Set<String> extensions = new HashSet<String>();
+
+ /**
+ * Creates a new selector for the given extensions.
+ *
+ * @param extensions
+ * The extensions to be included by this selector.
+ */
+ public FileExtensionSelector(final Collection<String> extensions)
+ {
+ if (extensions != null)
+ {
+ this.extensions.addAll(extensions);
+ }
+ }
+
+ /**
+ * Creates a new selector for the given extensions.
+ *
+ * @param extensions
+ * The extensions to be included by this selector.
+ */
+ public FileExtensionSelector(final String... extensions)
+ {
+ if (extensions != null)
+ {
+ this.extensions.addAll(Arrays.asList(extensions));
+ }
+ }
+
+ /**
+ * Determines if a file or folder should be selected.
+ *
+ * @param fileInfo
+ * The file selection information.
+ * @return true if the file should be selected, false otherwise.
+ */
+ @Override
+ public boolean includeFile(final FileSelectInfo fileInfo)
+ {
+ if (this.extensions == null)
+ {
+ return false;
+ }
+ for (final String extension : this.extensions)
+ {
+ if (fileInfo.getFile().getName().getExtension().equalsIgnoreCase(extension))
+ {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Determines whether a folder should be traversed.
+ *
+ * @param fileInfo
+ * The file selection information.
+ * @return true if descendants should be traversed, fase otherwise.
+ */
+ @Override
+ public boolean traverseDescendents(final FileSelectInfo fileInfo)
+ {
+ return true;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileFilter.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileFilter.java
new file mode 100644
index 0000000..828619f
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileFilter.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+/**
+ * This interface is used to select files when traversing the direct children of the base.
+ */
+public interface FileFilter
+{
+ /**
+ * Determines if a file or folder should be selected.
+ *
+ * @param fileInfo the file or folder to select.
+ * @return true if the file should be selected.
+ */
+ boolean accept(final FileSelectInfo fileInfo);
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileFilterSelector.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileFilterSelector.java
new file mode 100644
index 0000000..3b65dde
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileFilterSelector.java
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+import org.apache.commons.vfs2.util.Messages;
+
+/**
+ * A {@link org.apache.commons.vfs2.FileSelector} that selects all children of the given fileObject.
+ * <p>
+ * This is to mimic the {@link java.io.FileFilter} interface.
+ */
+public class FileFilterSelector extends FileDepthSelector
+{
+ /**
+ * The FileFilter.
+ */
+ private final FileFilter fileFilter;
+
+ public FileFilterSelector()
+ {
+ this(null);
+ }
+
+ public FileFilterSelector(final FileFilter fileFilter)
+ {
+ super(1, 1);
+ this.fileFilter = fileFilter;
+ }
+
+ /**
+ * Determines if a file or folder should be selected.
+ * @param fileInfo The file selection information.
+ * @return true if the file or folder should be included, false otherwise.
+ */
+ @Override
+ public boolean includeFile(final FileSelectInfo fileInfo)
+ {
+ if (!super.includeFile(fileInfo))
+ {
+ return false;
+ }
+
+ return accept(fileInfo);
+ }
+
+ /**
+ * Determines whether the file should be selected.
+ * @param fileInfo The file selection information.
+ * @return true if the file should be selected, false otherwise.
+ */
+ public boolean accept(final FileSelectInfo fileInfo)
+ {
+ if (fileFilter != null)
+ {
+ return fileFilter.accept(fileInfo);
+ }
+
+ throw new IllegalArgumentException(Messages.getString("vfs.selectors/filefilter.missing.error"));
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileListener.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileListener.java
new file mode 100644
index 0000000..06c016e
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileListener.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+/**
+ * Listens for changes to a file.
+ */
+public interface FileListener
+{
+ /**
+ * Called when a file is created.
+ *
+ * @param event The FileChangeEvent.
+ * @throws Exception if an error occurs.
+ */
+ void fileCreated(FileChangeEvent event) throws Exception;
+
+ /**
+ * Called when a file is deleted.
+ *
+ * @param event The FileChangeEvent.
+ * @throws Exception if an error occurs.
+ */
+ void fileDeleted(FileChangeEvent event) throws Exception;
+
+ /**
+ * Called when a file is changed.
+ * <p>
+ * This will only happen if you monitor the file using {@link FileMonitor}.
+ *
+ * @param event The FileChangeEvent.
+ * @throws Exception if an error occurs.
+ */
+ void fileChanged(FileChangeEvent event) throws Exception;
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileMonitor.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileMonitor.java
new file mode 100644
index 0000000..716ef27
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileMonitor.java
@@ -0,0 +1,35 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+/**
+ * FileMonitor interface.
+ */
+public interface FileMonitor
+{
+ /**
+ * Adds a file to be monitored.
+ * @param file The FileObject to monitor.
+ */
+ void addFile(final FileObject file);
+
+ /**
+ * Removes a file from being monitored.
+ * @param file The FileObject to stop monitoring.
+ */
+ void removeFile(final FileObject file);
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileName.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileName.java
new file mode 100644
index 0000000..6dce63f
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileName.java
@@ -0,0 +1,227 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+/**
+ * Represents a file name. File names are immutable, and work correctly as
+ * keys in hash tables.
+ *
+ * @see FileObject
+ */
+public interface FileName extends Comparable<FileName>
+{
+ /**
+ * The separator character used in file paths.
+ */
+ char SEPARATOR_CHAR = '/';
+
+ /**
+ * The separator used in file paths.
+ */
+ String SEPARATOR = "/";
+
+ /**
+ * The absolute path of the root of a file system.
+ */
+ String ROOT_PATH = "/";
+
+ /**
+ * Returns the base name of this file. The base name is the last element
+ * of the file name. For example the base name of
+ * {@code /somefolder/somefile} is {@code somefile}.
+ * <p>
+ * The root file of a file system has an empty base name.
+ * </p>
+ *
+ * @return The base name. Never returns null.
+ */
+ String getBaseName();
+
+ /**
+ * Returns the absolute path of this file, within its file system. This
+ * path is normalized, so that {@code .} and {@code ..} elements
+ * have been removed. Also, the path only contains {@code /} as its
+ * separator character. The path always starts with {@code /}
+ * <p>
+ * The root of a file system has {@code /} as its absolute path.
+ * </p>
+ *
+ * @return The path. Never returns null.
+ */
+ String getPath();
+
+ /**
+ * Returns the absolute path of this file, within its file system. This
+ * path is normalized, so that {@code .} and {@code ..} elements
+ * have been removed. Also, the path only contains {@code /} as its
+ * separator character. The path always starts with {@code /}
+ * <p>
+ * The root of a file system has {@code /} as its absolute path.
+ * </p>
+ * <p>
+ * In contrast to {@link #getPath()} the path is decoded i.e. all %nn stuff
+ * replaced by its character.
+ * </p>
+ *
+ * @return The path. Never returns null.
+ * @throws FileSystemException if the path is not correctly encoded
+ */
+ String getPathDecoded() throws FileSystemException;
+
+ /**
+ * Returns the extension of this file name.
+ *
+ * @return The extension. Returns an empty string if the name has no
+ * extension.
+ */
+ String getExtension();
+
+ /**
+ * Returns the depth of this file name, within its file system. The depth
+ * of the root of a file system is 0. The depth of any other file is
+ * 1 + the depth of its parent.
+ *
+ * @return The depth of this file name.
+ */
+ int getDepth();
+
+ /**
+ * Returns the URI scheme of this file.
+ *
+ * @return The URI scheme of this file.
+ */
+ String getScheme();
+
+ /**
+ * Returns the absolute URI of this file.
+ *
+ * @return the absolute URI of this file.
+ */
+ String getURI();
+
+ /**
+ * Returns the root URI of the file system this file belongs to.
+ *
+ * @return the root URI.
+ */
+ String getRootURI();
+
+ /**
+ * Finds the root of the file system.
+ *
+ * @return the file system root.
+ */
+ FileName getRoot();
+
+ /**
+ * Returns the file name of the parent of this file. The root of a
+ * file system has no parent.
+ *
+ * @return A {@link FileName} object representing the parent name. Returns
+ * null for the root of a file system.
+ */
+ FileName getParent();
+
+ /**
+ * Resolves a name, relative to this file name. Equivalent to calling
+ * {@code resolveName( path, NameScope.FILE_SYSTEM )}.
+ *
+ * @param name The name to resolve.
+ * @return A {@link FileName} object representing the resolved file name.
+ * @throws FileSystemException If the name is invalid.
+ */
+ // FileName resolveName(String name) throws FileSystemException;
+
+ /**
+ * Resolves a name, relative to this file name. Refer to {@link NameScope}
+ * for a description of how names are resolved.
+ *
+ * @param name The name to resolve.
+ * @param scope The scope to use when resolving the name.
+ * @return A {@link FileName} object representing the resolved file name.
+ * @throws FileSystemException If the name is invalid.
+ */
+ // FileName resolveName(String name, NameScope scope)
+ // throws FileSystemException;
+
+ /**
+ * Converts a file name to a relative name, relative to this file name.
+ *
+ * @param name The name to convert to a relative path.
+ * @return The relative name.
+ * @throws FileSystemException On error.
+ */
+ String getRelativeName(FileName name) throws FileSystemException;
+
+ /**
+ * Determines if another file name is an ancestor of this file name.
+ *
+ * @param ancestor The FileName to check.
+ * @return true if another file name is an ancestor of this file name.
+ */
+ boolean isAncestor(FileName ancestor);
+
+ /**
+ * Determines if another file name is a descendent of this file name.
+ *
+ * @param descendent the FileName to check.
+ * @return true if the other FileName is a descendent of this file name.
+ */
+ boolean isDescendent(FileName descendent);
+
+ /**
+ * Determines if another file name is a descendent of this file name.
+ *
+ * @param descendent the FileName to check.
+ * @param nameScope the NameScope of the FileName.
+ * @return true if the other FileName is a descendent of this file name.
+ */
+ boolean isDescendent(FileName descendent, NameScope nameScope);
+
+ /**
+ * Checks if this file name is a name for a regular file.
+ *
+ * @return true if this file name is a name for a regular file.
+ * @throws FileSystemException if an error occurs.
+ * @see #getType()
+ * @see FileType#FILE
+ * @since 2.1
+ */
+ boolean isFile() throws FileSystemException;
+
+ /**
+ * Returns the requested or current type of this name.
+ * <p>
+ * The "requested" type is the one determined during resolving the name.
+ * In this case the name is a {@link FileType#FOLDER} if it ends with an "/" else
+ * it will be a {@link FileType#FILE}.
+ * <p>
+ * Once attached it will be changed to reflect the real type of this resource.
+ *
+ * @return {@link FileType#FOLDER} or {@link FileType#FILE}
+ */
+ FileType getType();
+
+ /**
+ * Returns a "friendly path", this is a path without a password.
+ * <p>
+ * This path can not be used to resolve the path again.
+ *
+ * @return the friendly URI as a String.
+ */
+ String getFriendlyURI();
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileNotFolderException.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileNotFolderException.java
new file mode 100644
index 0000000..48b8066
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileNotFolderException.java
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+/**
+ * Delivers a file-not-folder exception which happens when trying to issue {@link FileObject#getChildren()} on a file.
+ * @since 2.0
+ */
+public class FileNotFolderException extends FileSystemException
+{
+ /**
+ * serialVersionUID format is YYYYMMDD for the date of the last binary change.
+ */
+ private static final long serialVersionUID = 20101208L;
+
+ public FileNotFolderException(final Object info0)
+ {
+ super("vfs.provider/list-children-not-folder.error", info0);
+ }
+
+ public FileNotFolderException(final Object info0, final Throwable throwable)
+ {
+ super("vfs.provider/list-children-not-folder.error", info0, throwable);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileNotFoundException.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileNotFoundException.java
new file mode 100644
index 0000000..04e5333
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileNotFoundException.java
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+/**
+ * delivers a file-not-found exception.
+ * @since 2.0
+ */
+public class FileNotFoundException extends FileSystemException
+{
+ /**
+ * serialVersionUID format is YYYYMMDD for the date of the last binary change.
+ */
+ private static final long serialVersionUID = 20101208L;
+
+ public FileNotFoundException(final Object info0)
+ {
+ super("vfs.provider/read-not-file.error", info0);
+ }
+
+ public FileNotFoundException(final Object info0, final Throwable throwable)
+ {
+ super("vfs.provider/read-not-file.error", info0, throwable);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileObject.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileObject.java
new file mode 100644
index 0000000..9c5124f
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileObject.java
@@ -0,0 +1,456 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+import java.io.Closeable;
+import java.net.URL;
+import java.util.List;
+
+import org.apache.commons.vfs2.operations.FileOperations;
+
+/**
+ * Represents a file, and is used to access the content and
+ * structure of the file.
+ * <p>
+ * Files are arranged in a hierarchy. Each hierarchy forms a
+ * <i>file system</i>. A file system represents things like a local OS
+ * file system, a windows share, an HTTP server, or the contents of a Zip file.
+ * <p>
+ * There are two types of files: <i>Folders</i>, which contain other files,
+ * and <i>normal files</i>, which contain data, or <i>content</i>. A folder may
+ * not have any content, and a normal file cannot contain other files.
+ *
+ * <h2>File Naming</h2>
+ *
+ * TODO - write this.
+ *
+ * <h2>Reading and Writing a File</h2>
+ *
+ * Reading and writing a file, and all other operations on the file's
+ * <i>content</i>, is done using the {@link FileContent} object returned
+ * by {@link #getContent}.
+
+ * <h2>Creating and Deleting a File</h2>
+ *
+ * A file is created using either {@link #createFolder}, {@link #createFile},
+ * or by writing to the file using one of the {@link FileContent} methods.
+ * <p>
+ * A file is deleted using {@link #delete}. Recursive deletion can be
+ * done using {@link #delete(FileSelector)}.
+ *
+ * <h2>Finding Files</h2>
+ *
+ * Other files in the <i>same</i> file system as this file can be found
+ * using:
+ * <ul>
+ * <li>{@link #findFiles} to find a set of matching descendants in in the same file system.</li>
+ * <li>{@link #getChildren} and {@link #getChild} to find the children of this file.</li>
+ * <li>{@link #getParent} to find the folder containing this file.</li>
+ * <li>{@link #getFileSystem} to find another file in the same file system.</li>
+ * <li>{@link #resolveFile} to find another file relative to this file.</li>
+ * </ul>
+ * To find files in another file system, use a {@link FileSystemManager}.
+ *
+ * <h2>Iterating Files</h2>
+ *
+ * You can iterate over a FileObject using the Java "foreach" statement, which provides all descendants of a File
+ * Object.
+ *
+ * <h2>Sorting Files</h2>
+ *
+ * Files may be sorted using {@link java.util.Arrays#sort(Object[]) Arrays.sort()}
+ * and {@link java.util.Collections#sort(List) Collections.sort()}.
+ *
+ * @see FileSystemManager
+ * @see FileContent
+ * @see FileName
+ */
+public interface FileObject extends Comparable<FileObject>, Iterable<FileObject>, Closeable
+{
+ /**
+ * Queries the file if it is possible to rename it to newfile.
+ *
+ * @param newfile the new file(-name)
+ * @return true it this is the case
+ */
+ boolean canRenameTo(FileObject newfile);
+
+ /**
+ * Closes this file, and its content. This method is a hint to the
+ * implementation that it can release any resources associated with
+ * the file.
+ * <p>
+ * The file object can continue to be used after this method is called.
+ * </p>
+ *
+ * @throws FileSystemException On error closing the file.
+ * @see FileContent#close
+ */
+ @Override
+ void close() throws FileSystemException;
+
+ /**
+ * Copies another file, and all its descendants, to this file.
+ * <p>
+ * If this file does not exist, it is created. Its parent folder is also
+ * created, if necessary. If this file does exist, it is deleted first.
+ * </p>
+ * <p>
+ * This method is not transactional. If it fails and throws an
+ * exception, this file will potentially only be partially copied.
+ * </p>
+ *
+ * @param srcFile The source file to copy.
+ * @param selector The selector to use to select which files to copy.
+ * @throws FileSystemException If this file is read-only, or if the source file does not exist,
+ * or on error copying the file.
+ */
+ void copyFrom(FileObject srcFile, FileSelector selector)
+ throws FileSystemException;
+
+ /**
+ * Creates this file, if it does not exist. Also creates any ancestor
+ * folders which do not exist. This method does nothing if the file
+ * already exists and is a file.
+ *
+ * @throws FileSystemException If the file already exists with the wrong type, or the parent
+ * folder is read-only, or on error creating this file or one of
+ * its ancestors.
+ */
+ void createFile() throws FileSystemException;
+
+ /**
+ * Creates this folder, if it does not exist. Also creates any ancestor
+ * folders which do not exist. This method does nothing if the folder
+ * already exists.
+ *
+ * @throws FileSystemException If the folder already exists with the wrong type, or the parent
+ * folder is read-only, or on error creating this folder or one of
+ * its ancestors.
+ */
+ void createFolder() throws FileSystemException;
+
+ /**
+ * Deletes this file. Does nothing if this file does not exist of if it is a
+ * folder that has children. Does not delete any descendants of this file,
+ * use {@link #delete(FileSelector)} or {@link #deleteAll()} for that.
+ *
+ * @return true if this object has been deleted
+ * @throws FileSystemException If this file is a non-empty folder, or if this file is read-only,
+ * or on error deleteing this file.
+ */
+ boolean delete() throws FileSystemException;
+
+ /**
+ * Deletes all descendants of this file that match a selector. Does
+ * nothing if this file does not exist.
+ *
+ * <p>This method is not transactional. If it fails and throws an
+ * exception, this file will potentially only be partially deleted.
+ * </p>
+ *
+ * @param selector The selector to use to select which files to delete.
+ * @return the number of deleted objects
+ * @throws FileSystemException If this file or one of its descendants is read-only, or on error
+ * deleting this file or one of its descendants.
+ */
+ int delete(FileSelector selector) throws FileSystemException;
+
+ /**
+ * Deletes this file and all children.
+ *
+ * @return the number of deleted files.
+ * @throws FileSystemException if an error occurs.
+ * @see #delete(FileSelector)
+ * @see Selectors#SELECT_ALL
+ */
+ int deleteAll() throws FileSystemException;
+
+ /**
+ * Determines if this file exists.
+ *
+ * @return {@code true} if this file exists, {@code false} if not.
+ * @throws FileSystemException On error determining if this file exists.
+ */
+ boolean exists() throws FileSystemException;
+
+ /**
+ * Finds the set of matching descendants of this file, in depthwise order.
+ *
+ * @param selector The selector to use to select matching files.
+ * @return The matching files. The files are returned in depthwise order
+ * (that is, a child appears in the list before its parent).
+ * @throws FileSystemException if an error occurs.
+ */
+ FileObject[] findFiles(FileSelector selector) throws FileSystemException;
+
+ /**
+ * Finds the set of matching descendants of this file.
+ *
+ * @param selector the selector used to determine if the file should be selected
+ * @param depthwise controls the ordering in the list. e.g. deepest first
+ * @param selected container for selected files. list needs not to be empty.
+ * @throws FileSystemException if an error occurs.
+ */
+ void findFiles(FileSelector selector, boolean depthwise, List<FileObject> selected) throws FileSystemException;
+
+ /**
+ * Returns a child of this file. Note that this method returns {@code null}
+ * when the child does not exist. This differs from
+ * {@link #resolveFile(String, NameScope)} which never returns null.
+ *
+ * @param name The name of the child.
+ * @return The child, or null if there is no such child.
+ * @throws FileSystemException If this file does not exist, or is not a folder, or on error
+ * determining this file's children.
+ */
+ FileObject getChild(String name) throws FileSystemException;
+
+ /**
+ * Lists the children of this file.
+ *
+ * @return An array containing the children of this file. The array is
+ * unordered. If the file does not have any children, a zero-length
+ * array is returned. This method never returns null.
+ * @throws FileSystemException If this file does not exist, or is not a folder, or on error
+ * listing this file's children.
+ */
+ FileObject[] getChildren() throws FileSystemException;
+
+ /**
+ * Returns this file's content. The {@link FileContent} returned by this
+ * method can be used to read and write the content of the file.
+ *
+ * <p>This method can be called if the file does not exist, and
+ * the returned {@link FileContent} can be used to create the file
+ * by writing its content.
+ * </p>
+ *
+ * @return This file's content.
+ * @throws FileSystemException On error getting this file's content.
+ */
+ FileContent getContent() throws FileSystemException;
+
+ /**
+ * @return FileOperations interface that provides access to the operations API.
+ * @throws FileSystemException if an error occurs.
+ */
+ FileOperations getFileOperations() throws FileSystemException;
+
+ /**
+ * Returns the file system that contains this file.
+ *
+ * @return The file system.
+ */
+ FileSystem getFileSystem();
+
+ /**
+ * Returns the name of this file.
+ *
+ * @return the FileName.
+ */
+ FileName getName();
+
+ /**
+ * Returns the folder that contains this file.
+ *
+ * @return The folder that contains this file. Returns null if this file is
+ * the root of a file system.
+ * @throws FileSystemException On error finding the file's parent.
+ */
+ FileObject getParent() throws FileSystemException;
+
+ /**
+ * Returns the receiver as a URI String for public display, like, without a
+ * password.
+ *
+ * @return A URI String without a password, never {@code null}.
+ */
+ String getPublicURIString();
+
+ /**
+ * Returns this file's type.
+ *
+ * @return One of the {@link FileType} constants. Never returns null.
+ * @throws FileSystemException On error determining the file's type.
+ */
+ FileType getType() throws FileSystemException;
+
+ /**
+ * Returns a URL representing this file.
+ *
+ * @return the URL for the file.
+ * @throws FileSystemException if an error occurs.
+ */
+ URL getURL() throws FileSystemException;
+
+ /**
+ * Checks if the fileObject is attached.
+ *
+ * @return true if the FileObject is attached.
+ */
+ boolean isAttached();
+
+ /**
+ * Checks if someone reads/write to this file.
+ *
+ * @return true if the file content is open.
+ */
+ boolean isContentOpen();
+
+ /**
+ * Determines if this file is executable.
+ *
+ * @return {@code true} if this file is executable, {@code false} if not.
+ * @throws FileSystemException On error determining if this file exists.
+ */
+ boolean isExecutable() throws FileSystemException;
+
+ /**
+ * Checks if this file is a regular file.
+ *
+ * @return true if this file is a regular file.
+ * @throws FileSystemException if an error occurs.
+ * @see #getType()
+ * @see FileType#FILE
+ * @since 2.1
+ */
+ boolean isFile() throws FileSystemException;
+
+ /**
+ * Checks if this file is a folder.
+ *
+ * @return true if this file is a folder.
+ * @throws FileSystemException if an error occurs.
+ * @see #getType()
+ * @see FileType#FOLDER
+ * @since 2.1
+ */
+ boolean isFolder() throws FileSystemException;
+
+ /**
+ * Determines if this file is hidden.
+ *
+ * @return {@code true} if this file is hidden, {@code false} if not.
+ * @throws FileSystemException On error determining if this file exists.
+ */
+ boolean isHidden() throws FileSystemException;
+
+ /**
+ * Determines if this file can be read.
+ *
+ * @return {@code true} if this file is readable, {@code false} if not.
+ * @throws FileSystemException On error determining if this file exists.
+ */
+ boolean isReadable() throws FileSystemException;
+
+ /**
+ * Determines if this file can be written to.
+ *
+ * @return {@code true} if this file is writeable, {@code false} if not.
+ * @throws FileSystemException On error determining if this file exists.
+ */
+ boolean isWriteable() throws FileSystemException;
+
+ /**
+ * Move this file.
+ *
+ * <p>
+ * If the destFile exists, it is deleted first.
+ * </p>
+ *
+ * @param destFile the New filename.
+ * @throws FileSystemException If this file is read-only, or if the source file does not exist,
+ * or on error copying the file.
+ */
+ void moveTo(FileObject destFile)
+ throws FileSystemException;
+
+ /**
+ * This will prepare the fileObject to get resynchronized with the underlying file system if required.
+ *
+ * @throws FileSystemException if an error occurs.
+ */
+ void refresh() throws FileSystemException;
+
+ /**
+ * Finds a file, relative to this file. Equivalent to calling
+ * {@code resolveFile( path, NameScope.FILE_SYSTEM )}.
+ *
+ * @param path The path of the file to locate. Can either be a relative
+ * path or an absolute path.
+ * @return The file.
+ * @throws FileSystemException On error parsing the path, or on error finding the file.
+ */
+ FileObject resolveFile(String path) throws FileSystemException;
+
+ /**
+ * Finds a file relative to this file.
+ *
+ * Refer to {@link NameScope} for a description of how names are resolved in the different scopes.
+ *
+ * @param name The name to resolve.
+ * @param scope the NameScope for the file.
+ * @return The file.
+ * @throws FileSystemException On error parsing the path, or on error finding the file.
+ */
+ FileObject resolveFile(String name, NameScope scope)
+ throws FileSystemException;
+
+ /**
+ * Sets the owner's (or everybody's) write permission.
+ *
+ * @param executable
+ * True to allow read access, false to disallow.
+ * @param ownerOnly
+ * If {@code true}, the permission applies only to the owner; otherwise, it applies to everybody.
+ * @return true if the operation succeeded.
+ * @throws FileSystemException
+ * On error determining if this file exists.
+ * @since 2.1
+ */
+ boolean setExecutable(boolean executable, boolean ownerOnly) throws FileSystemException;
+
+
+ /**
+ * Sets the owner's (or everybody's) read permission.
+ *
+ * @param readable
+ * True to allow read access, false to disallow
+ * @param ownerOnly
+ * If {@code true}, the permission applies only to the owner; otherwise, it applies to everybody.
+ * @return true if the operation succeeded
+ * @throws FileSystemException
+ * On error determining if this file exists.
+ * @since 2.1
+ */
+ boolean setReadable(boolean readable, boolean ownerOnly) throws FileSystemException;
+
+ /**
+ * Sets the owner's (or everybody's) write permission.
+ *
+ * @param writable
+ * True to allow read access, false to disallow
+ * @param ownerOnly
+ * If {@code true}, the permission applies only to the owner; otherwise, it applies to everybody.
+ * @return true if the operation succeeded
+ * @throws FileSystemException
+ * On error determining if this file exists.
+ * @since 2.1
+ */
+ boolean setWritable(boolean writable, boolean ownerOnly) throws FileSystemException;
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileSelectInfo.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileSelectInfo.java
new file mode 100644
index 0000000..dcb6f9c
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileSelectInfo.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+/**
+ * Information about a file, that is used to select files during the
+ * traversal of a hierarchy.
+ * <p>
+ * TODO - Rename this interface, as it is used by both FileSelector and FileVisitor.
+ */
+public interface FileSelectInfo
+{
+ /**
+ * Returns the base folder of the traversal.
+ * @return FileObject representing the base folder.
+ */
+ FileObject getBaseFolder();
+
+ /**
+ * Returns the file (or folder) to be considered.
+ * @return The FileObject.
+ */
+ FileObject getFile();
+
+ /**
+ * Returns the depth of the file relative to the base folder.
+ * @return The depth of the file relative to the base folder.
+ */
+ int getDepth();
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileSelector.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileSelector.java
new file mode 100644
index 0000000..e6bdffc
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileSelector.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+/**
+ * This interface is used to select files when traversing a file hierarchy.
+ *
+ * @see Selectors
+ */
+public interface FileSelector
+{
+ /**
+ * Determines if a file or folder should be selected. This method is
+ * called in depthwise order (that is, it is called for the children
+ * of a folder before it is called for the folder itself).
+ *
+ * @param fileInfo the file or folder to select.
+ * @return true if the file should be selected.
+ * @throws Exception if an error occurs.
+ */
+ boolean includeFile(FileSelectInfo fileInfo)
+ throws Exception;
+
+ /**
+ * Determines whether a folder should be traversed. If this method returns
+ * true, {@link #includeFile} is called for each of the children of
+ * the folder, and each of the child folders is recursively traversed.
+ * <p>
+ * This method is called on a folder before {@link #includeFile}
+ * is called.
+ *
+ * @param fileInfo the file or folder to select.
+ * @return true if the folder should be traversed.
+ * @throws Exception if an error occurs.
+ */
+ boolean traverseDescendents(FileSelectInfo fileInfo)
+ throws Exception;
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileSystem.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileSystem.java
new file mode 100644
index 0000000..72069dd
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileSystem.java
@@ -0,0 +1,195 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+import java.io.File;
+
+/**
+ * A file system, made up of a hierarchy of files.
+ */
+public interface FileSystem
+{
+ /**
+ * Returns the root file of this file system.
+ * @return The root FileObject.
+ * @throws FileSystemException if an error occurs.
+ */
+ FileObject getRoot() throws FileSystemException;
+
+ /**
+ * Returns the name of the root file of this file system. The root name always
+ * contains a path String of "/".
+ * @return the root FileName.
+ */
+ FileName getRootName();
+
+ /**
+ * The root URI passed as a file system option or obtained from the rootName.
+ * @return The root URI.
+ */
+ String getRootURI();
+
+ /**
+ * Determines if this file system has a particular capability.
+ * <p>
+ * TODO - Move this to another interface, so that set of capabilities can be queried.
+ *
+ * @param capability The capability to check for.
+ * @return true if this filesystem has the requested capability.
+ * Note that not all files in the file system may have the
+ * capability.
+ */
+ boolean hasCapability(Capability capability);
+
+ /**
+ * Returns the parent layer if this is a layered file system.
+ *
+ * @return The parent layer, or null if this is not a layered file system.
+ * @throws FileSystemException if an error occurs.
+ */
+ FileObject getParentLayer() throws FileSystemException;
+
+ /**
+ * Gets the value of an attribute of the file system.
+ * <p>
+ * TODO - change to {@code Map getAttributes()} instead?<br>
+ * TODO - define the standard attribute names, and define which attrs
+ * are guaranteed to be present.
+ *
+ * @param attrName The name of the attribute.
+ * @return The value of the attribute.
+ * @throws org.apache.commons.vfs2.FileSystemException
+ * If the file does not exist, or is being written, or if the
+ * attribute is unknown.
+ * @see org.apache.commons.vfs2.FileContent#getAttribute
+ */
+ Object getAttribute(String attrName) throws FileSystemException;
+
+ /**
+ * Sets the value of an attribute of the file's content. Creates the
+ * file if it does not exist.
+ *
+ * @param attrName The name of the attribute.
+ * @param value The value of the attribute.
+ * @throws FileSystemException If the file is read-only, or is being read, or if the attribute
+ * is not supported, or on error setting the attribute.
+ * @see FileContent#setAttribute
+ */
+ void setAttribute(String attrName, Object value)
+ throws FileSystemException;
+
+ /**
+ * Finds a file in this file system.
+ *
+ * @param name The name of the file.
+ * @return The file. Never returns null.
+ * @throws FileSystemException if an error occurs.
+ */
+ FileObject resolveFile(FileName name) throws FileSystemException;
+
+ /**
+ * Finds a file in this file system.
+ *
+ * @param name The name of the file. This must be an absolute path.
+ * @return The file. Never returns null.
+ * @throws FileSystemException if an error occurs.
+ */
+ FileObject resolveFile(String name) throws FileSystemException;
+
+ /**
+ * Adds a listener on a file in this file system.
+ *
+ * @param file The file to attach the listener to.
+ * @param listener The listener to add.
+ */
+ void addListener(FileObject file, FileListener listener);
+
+ /**
+ * Removes a listener from a file in this file system.
+ *
+ * @param file The file to remove the listener from.
+ * @param listener The listener to remove.
+ */
+ void removeListener(FileObject file, FileListener listener);
+
+ /**
+ * Adds a junction to this file system. A junction is a link that attaches
+ * the supplied file to a point in this file system, making it look like
+ * part of the file system.
+ *
+ * @param junctionPoint The point in this file system to add the junction.
+ * @param targetFile The file to link to.
+ * @throws FileSystemException If this file system does not support junctions, or the junction
+ * point or target file is invalid (the file system may not support
+ * nested junctions, for example).
+ */
+ void addJunction(String junctionPoint, FileObject targetFile)
+ throws FileSystemException;
+
+ /**
+ * Removes a junction from this file system.
+ *
+ * @param junctionPoint The junction to remove.
+ * @throws FileSystemException On error removing the junction.
+ */
+ void removeJunction(String junctionPoint) throws FileSystemException;
+
+ /**
+ * Creates a temporary local copy of a file and its descendants. If
+ * this file is already a local file, a copy is not made.
+ * <p>
+ * Note that the local copy may include additonal files, that were
+ * not selected by the given selector.
+ * <p>
+ * TODO - Add options to indicate whether the caller is happy to deal with
+ * extra files being present locally (eg if the file has been
+ * replicated previously), or whether the caller expects only
+ * the selected files to be present.
+ *
+ * @param file The file to replicate.
+ * @param selector The selector to use to select the files to replicate.
+ * @return The local copy of this file.
+ * @throws FileSystemException If this file does not exist, or on error replicating the file.
+ */
+ File replicateFile(FileObject file, FileSelector selector)
+ throws FileSystemException;
+
+ /**
+ * Returns the FileSystemOptions used to instantiate this filesystem.
+ * @return The FileSystemOptions.
+ */
+ FileSystemOptions getFileSystemOptions();
+
+ /**
+ * Returns a reference to the FileSytemManager.
+ * @return The FileSystemManager.
+ */
+ FileSystemManager getFileSystemManager();
+
+ /**
+ * Returns the accuracy of the last modification time.
+ * <p>
+ * The local file provider is not very smart in figuring this out, for remote
+ * access to file systems the providers typically don't know the value of the underlying
+ * real file system.
+ *
+ * @return the accuracy of the last modification time in milliseconds. A
+ * value of 0 means perfectly accurate, anything {@literal > 0} might be off
+ * by this value. For example, sftp has an accuracy of 1000 ms.
+ */
+ double getLastModTimeAccuracy();
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileSystemConfigBuilder.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileSystemConfigBuilder.java
new file mode 100644
index 0000000..05966af
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileSystemConfigBuilder.java
@@ -0,0 +1,740 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+/**
+ * Abstract class which has the right to fill FileSystemOptions.
+ */
+public abstract class FileSystemConfigBuilder
+{
+ /** Default prefix to use when resolving system properties */
+ private static final String PREFIX = "vfs.";
+
+ /** The root uri of the file system */
+ private static final String ROOTURI = "rootURI";
+
+ /** The prefix to use when resolving system properties */
+ private final String prefix;
+
+ /**
+ * Construct builder with default prefix.
+ *
+ * @since 1.0
+ */
+ protected FileSystemConfigBuilder()
+ {
+ this.prefix = PREFIX;
+ }
+
+ /**
+ * Construct builder with specified component name.
+ *
+ * @param component component name to be used in prefix
+ *
+ * @since 2.0
+ */
+ protected FileSystemConfigBuilder(final String component)
+ {
+ this.prefix = PREFIX + component;
+ }
+
+ /**
+ * The root URI of the file system.
+ *
+ * @param opts the file system options to modify
+ * @param rootURI The creator name to be associated with the file.
+ *
+ * @since 2.0
+ */
+ public void setRootURI(final FileSystemOptions opts, final String rootURI)
+ {
+ setParam(opts, ROOTURI, rootURI);
+ }
+
+ /**
+ * Return the root URI of the file system.
+ *
+ * @param opts file system options to work with
+ * @return The root URI
+ *
+ * @since 2.0
+ */
+ public String getRootURI(final FileSystemOptions opts)
+ {
+ return getString(opts, ROOTURI);
+ }
+
+ /**
+ * Set named parameter.
+ *
+ * @param opts the file system options to modify
+ * @param name set option with this name
+ * @param value boolean value to set
+ *
+ * @since 2.1
+ */
+ protected void setParam(final FileSystemOptions opts, final String name, final boolean value)
+ {
+ setParam(opts, name, Boolean.valueOf(value));
+ }
+
+ /**
+ * Set named parameter.
+ *
+ * @param opts the file system options to modify
+ * @param name set option with this name
+ * @param value object value to set
+ *
+ * @since 1.0
+ */
+ protected void setParam(final FileSystemOptions opts, final String name, final Object value)
+ {
+ opts.setOption(getConfigClass(), name, value);
+ }
+
+ /**
+ * Get named parameter.
+ *
+ * @param opts file system options to work with
+ * @param name get option with this name
+ * @return the named option or null
+ *
+ * @since 1.0
+ */
+ protected Object getParam(final FileSystemOptions opts, final String name)
+ {
+ if (opts == null)
+ {
+ return null;
+ }
+
+ return opts.getOption(getConfigClass(), name);
+ }
+
+ /**
+ * Check if option exists.
+ *
+ * @param opts file system options to work with
+ * @param name the name to look up in {@code opts}
+ * @return true if opts have the named parameter
+ *
+ * @since 1.0
+ */
+ protected boolean hasParam(final FileSystemOptions opts, final String name)
+ {
+ return opts != null && opts.hasOption(getConfigClass(), name);
+ }
+
+ /**
+ * Is named setting specified.
+ *
+ * @param opts file system options to work with
+ * @param name the option to check in {@code opts} or system properties
+ * @return true if option exists
+ *
+ * @since 2.0
+ */
+ protected boolean hasObject(final FileSystemOptions opts, final String name)
+ {
+ return hasParam(opts, name) || System.getProperties().containsKey(toPropertyKey(name));
+ }
+
+ /**
+ * Get named option as boolean.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @return the option in {@code opts} or system properties, otherwise null
+ * @see #getBoolean(FileSystemOptions, String, Boolean)
+ *
+ * @since 2.0
+ */
+ protected Boolean getBoolean(final FileSystemOptions opts, final String name)
+ {
+ return getBoolean(opts, name, null);
+ }
+
+ /**
+ * Get named option as boolean.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @param defaultValue value to return if option is not present
+ * @return the option in {@code opts} or system properties, otherwise {@code defaultValue}
+ * @see #getBoolean(FileSystemOptions, String, Boolean)
+ *
+ * @since 2.0
+ */
+ protected boolean getBoolean(final FileSystemOptions opts, final String name, final boolean defaultValue)
+ {
+ return getBoolean(opts, name, Boolean.valueOf(defaultValue)).booleanValue();
+ }
+
+ /**
+ * Get named option as boolean.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @param defaultValue value to return if option is not present
+ * @return the option in {@code opts} or system properties, otherwise {@code defaultValue}
+ * @see #getBoolean(FileSystemOptions, String, Boolean)
+ *
+ * @since 2.0
+ */
+ protected Boolean getBoolean(final FileSystemOptions opts, final String name, final Boolean defaultValue)
+ {
+ Boolean value = (Boolean) getParam(opts, name);
+ if (value == null)
+ {
+ final String str = getProperty(name);
+ if (str == null)
+ {
+ return defaultValue;
+ }
+ value = Boolean.valueOf(str);
+ }
+ return value;
+ }
+
+ /**
+ * Get named option as byte.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @return the option in {@code opts} or system properties, otherwise null
+ * @see #getByte(FileSystemOptions, String, Byte)
+ *
+ * @since 2.0
+ */
+ protected Byte getByte(final FileSystemOptions opts, final String name)
+ {
+ return getByte(opts, name, null);
+ }
+
+ /**
+ * Get named option as byte.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @param defaultValue value to return if option is not present
+ * @return the option in {@code opts} or system properties, otherwise {@code defaultValue}
+ * @see #getByte(FileSystemOptions, String, Byte)
+ *
+ * @since 2.0
+ */
+ protected byte getByte(final FileSystemOptions opts, final String name, final byte defaultValue)
+ {
+ return getByte(opts, name, Byte.valueOf(defaultValue)).byteValue();
+ }
+
+ /**
+ * Get named option as byte.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @param defaultValue value to return if option is not present
+ * @return the option in {@code opts} or system properties, otherwise {@code defaultValue}
+ *
+ * @since 2.0
+ */
+ protected Byte getByte(final FileSystemOptions opts, final String name, final Byte defaultValue)
+ {
+ Byte value = (Byte) getParam(opts, name);
+ if (value == null)
+ {
+ final String str = getProperty(name);
+ if (str == null)
+ {
+ return defaultValue;
+ }
+ value = Byte.valueOf(str);
+ }
+ return value;
+ }
+
+ /**
+ * Get named option as character.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @return the option in {@code opts} or system properties, otherwise null
+ * @see #getCharacter(FileSystemOptions, String, Character)
+ *
+ * @since 2.0
+ */
+ protected Character getCharacter(final FileSystemOptions opts, final String name)
+ {
+ return getCharacter(opts, name, null);
+ }
+
+ /**
+ * Get named option as character.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @param defaultValue value to return if option is not present
+ * @return the option in {@code opts} or system properties, otherwise {@code defaultValue}
+ * @see #getCharacter(FileSystemOptions, String, Character)
+ *
+ * @since 2.0
+ */
+ protected char getCharacter(final FileSystemOptions opts, final String name, final char defaultValue)
+ {
+ return getCharacter(opts, name, new Character(defaultValue)).charValue();
+ }
+
+ /**
+ * Get named option as character.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @param defaultValue value to return if option is not present
+ * @return the option in {@code opts} or system properties, otherwise {@code defaultValue}
+ *
+ * @since 2.0
+ */
+ protected Character getCharacter(final FileSystemOptions opts, final String name, final Character defaultValue)
+ {
+ Character value = (Character) getParam(opts, name);
+ if (value == null)
+ {
+ final String str = getProperty(name);
+ if (str == null || str.length() <= 0)
+ {
+ return defaultValue;
+ }
+ value = new Character(str.charAt(0));
+ }
+ return value;
+ }
+
+ /**
+ * Get named option as double.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @return the option in {@code opts} or system properties, otherwise null
+ * @see #getDouble(FileSystemOptions, String, Double)
+ *
+ * @since 2.0
+ */
+ protected Double getDouble(final FileSystemOptions opts, final String name)
+ {
+ return getDouble(opts, name, null);
+ }
+
+ /**
+ * Get named option as double.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @param defaultValue value to return if option is not present
+ * @return the option in {@code opts} or system properties, otherwise {@code defaultValue}
+ * @see #getDouble(FileSystemOptions, String, Double)
+ *
+ * @since 2.0
+ */
+ protected double getDouble(final FileSystemOptions opts, final String name, final double defaultValue)
+ {
+ return getDouble(opts, name, new Double(defaultValue)).doubleValue();
+ }
+
+ /**
+ * Get named option as double.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @param defaultValue value to return if option is not present
+ * @return the option in {@code opts} or system properties, otherwise {@code defaultValue}
+ *
+ * @since 2.0
+ */
+ protected Double getDouble(final FileSystemOptions opts, final String name, final Double defaultValue)
+ {
+ Double value = (Double) getParam(opts, name);
+ if (value == null)
+ {
+ final String str = getProperty(name);
+ if (str == null || str.length() <= 0)
+ {
+ return defaultValue;
+ }
+ value = Double.valueOf(str);
+ }
+ return value;
+ }
+
+ /**
+ * Get named option as enumeration.
+ *
+ * @param <E> enumeration type
+ * @param enumClass class of enumeration type
+ * @param opts file system options to work with
+ * @param name the option name *
+ * @return the option in {@code opts} or system properties, otherwise null
+ * @see #getEnum(Class, FileSystemOptions, String, Enum)
+ * @throws IllegalArgumentException if option value is not a known enumeration.
+ *
+ * @since 2.1
+ */
+ protected <E extends Enum<E>> E getEnum(final Class<E> enumClass, final FileSystemOptions opts, final String name)
+ {
+ return this.<E>getEnum(enumClass, opts, name, null);
+ }
+
+ /**
+ * Get named option as enumeration.
+ *
+ * @param <E> enumeration type
+ * @param enumClass class of enumeration type
+ * @param opts file system options to work with
+ * @param name the option name
+ * @param defaultValue value to return if option is not present
+ * @return the option in {@code opts} or system properties, otherwise {@code defaultValue}
+ * @see #getEnum(Class, FileSystemOptions, String, Enum)
+ * @throws IllegalArgumentException if option value is not a known enumeration.
+ *
+ * @since 2.1
+ */
+ protected <E extends Enum<E>> E getEnum(final Class<E> enumClass, final FileSystemOptions opts,
+ final String name, final E defaultValue)
+ {
+ @SuppressWarnings("unchecked")
+ E value = (E) getParam(opts, name);
+ if (value == null)
+ {
+ final String str = getProperty(name);
+ if (str == null)
+ {
+ return defaultValue;
+ }
+ value = Enum.valueOf(enumClass, str);
+ }
+ return value;
+ }
+
+ /**
+ * Get named option as float.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @return the option in {@code opts} or system properties, otherwise null
+ * @see #getFloat(FileSystemOptions, String, Float)
+ * @throws NumberFormatException if option value is not a valid float.
+ *
+ * @since 2.0
+ */
+ protected Float getFloat(final FileSystemOptions opts, final String name)
+ {
+ return getFloat(opts, name, null);
+ }
+
+ /**
+ * Get named option as float.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @param defaultValue value to return if option is not present
+ * @return the option in {@code opts} or system properties, otherwise {@code defaultValue}
+ * @see #getFloat(FileSystemOptions, String, Float)
+ * @throws NumberFormatException if option value is not a valid float.
+ *
+ * @since 2.0
+ */
+ protected float getFloat(final FileSystemOptions opts, final String name, final float defaultValue)
+ {
+ return getFloat(opts, name, new Float(defaultValue)).floatValue();
+ }
+
+ /**
+ * Get named option as float.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @param defaultValue value to return if option is not present
+ * @return the option in {@code opts} or system properties, otherwise {@code defaultValue}
+ * @throws NumberFormatException if option value is not a valid float.
+ *
+ * @since 2.0
+ */
+ protected Float getFloat(final FileSystemOptions opts, final String name, final Float defaultValue)
+ {
+ Float value = (Float) getParam(opts, name);
+ if (value == null)
+ {
+ final String str = getProperty(name);
+ if (str == null || str.length() <= 0)
+ {
+ return defaultValue;
+ }
+ value = Float.valueOf(str);
+ }
+ return value;
+ }
+
+ /**
+ * Get named option as integer.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @return the option in {@code opts} or system properties, otherwise null
+ * @see #getInteger(FileSystemOptions, String, Integer)
+ * @throws NumberFormatException if option value is not a valid integer.
+ *
+ * @since 2.0
+ */
+ protected Integer getInteger(final FileSystemOptions opts, final String name)
+ {
+ return getInteger(opts, name, null);
+ }
+
+ /**
+ * Get named option as integer.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @param defaultValue value to return if option is not present
+ * @return the option in {@code opts} or system properties, otherwise {@code defaultValue}
+ * @see #getInteger(FileSystemOptions, String, Integer)
+ * @throws NumberFormatException if option value is not a valid integer.
+ *
+ * @since 2.0
+ */
+ protected int getInteger(final FileSystemOptions opts, final String name, final int defaultValue)
+ {
+ return getInteger(opts, name, Integer.valueOf(defaultValue)).intValue();
+ }
+
+ /**
+ * Get named option as integer.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @param defaultValue value to return if option is not present
+ * @return the option in {@code opts} or system properties, otherwise {@code defaultValue}
+ * @throws NumberFormatException if option value is not a valid integer.
+ *
+ * @since 2.0
+ */
+ protected Integer getInteger(final FileSystemOptions opts, final String name, final Integer defaultValue)
+ {
+ Integer value = (Integer) getParam(opts, name);
+ if (value == null)
+ {
+ final String str = getProperty(name);
+ if (str == null)
+ {
+ return defaultValue;
+ }
+ value = Integer.valueOf(str);
+ }
+ return value;
+ }
+
+ /**
+ * Get named option as long.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @return the option in {@code opts} or system properties, otherwise null
+ * @see #getLong(FileSystemOptions, String, Long)
+ * @throws NumberFormatException if option value is not a valid long.
+ *
+ * @since 2.0
+ */
+ protected Long getLong(final FileSystemOptions opts, final String name)
+ {
+ return getLong(opts, name, null);
+ }
+
+ /**
+ * Get named option as long.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @param defaultValue value to return if option is not present
+ * @return the option in {@code opts} or system properties, otherwise {@code defaultValue}
+ * @see #getLong(FileSystemOptions, String, Long)
+ * @throws NumberFormatException if option value is not a valid long.
+ *
+ * @since 2.0
+ */
+ protected long getLong(final FileSystemOptions opts, final String name, final long defaultValue)
+ {
+ return getLong(opts, name, Long.valueOf(defaultValue)).longValue();
+ }
+
+ /**
+ * Get named option as long.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @param defaultValue value to return if option is not present
+ * @return the option in {@code opts} or system properties, otherwise {@code defaultValue}
+ * @throws NumberFormatException if option value is not a valid long.
+ *
+ * @since 2.0
+ */
+ protected Long getLong(final FileSystemOptions opts, final String name, final Long defaultValue)
+ {
+ Long value = (Long) getParam(opts, name);
+ if (value == null)
+ {
+ final String str = getProperty(name);
+ if (str == null)
+ {
+ return defaultValue;
+ }
+ value = Long.valueOf(str);
+ }
+ return value;
+ }
+
+ /**
+ * Get named option as short.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @return the option in {@code opts} or system properties, otherwise null
+ * @see #getShort(FileSystemOptions, String, Short)
+ * @throws NumberFormatException if option value is not a valid short.
+ *
+ * @since 2.0
+ */
+ protected Short getShort(final FileSystemOptions opts, final String name)
+ {
+ return getShort(opts, name, null);
+ }
+
+ /**
+ * Get named option as short.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @param defaultValue value to return if option is not present
+ * @return the option in {@code opts} or system properties, otherwise {@code defaultValue}
+ * @see #getShort(FileSystemOptions, String, Short)
+ * @throws NumberFormatException if option value is not a valid short
+ *
+ * @since 2.0
+ */
+ protected short getShort(final FileSystemOptions opts, final String name, final short defaultValue)
+ {
+ return getShort(opts, name, Short.valueOf(defaultValue)).shortValue();
+ }
+
+ /**
+ * Get named option as short.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @param defaultValue value to return if option is not present
+ * @return the option in {@code opts} or system properties, otherwise {@code defaultValue}
+ * @throws NumberFormatException if option value is not a valid short
+ *
+ * @since 2.0
+ */
+ protected Short getShort(final FileSystemOptions opts, final String name, final Short defaultValue)
+ {
+ Short value = (Short) getParam(opts, name);
+ if (value == null)
+ {
+ final String str = getProperty(name);
+ if (str == null)
+ {
+ return defaultValue;
+ }
+ value = Short.valueOf(str);
+ }
+ return value;
+ }
+
+ /**
+ * Get named option as String.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @return the option in {@code opts} or system properties, otherwise null
+ * @see #getString(FileSystemOptions, String, String)
+ *
+ * @since 2.0
+ */
+ protected String getString(final FileSystemOptions opts, final String name)
+ {
+ return getString(opts, name, null);
+ }
+
+ /**
+ * Get named option as String.
+ *
+ * @param opts file system options to work with
+ * @param name the option name
+ * @param defaultValue value to return if option is not present
+ * @return the option in {@code opts} or system properties, otherwise {@code defaultValue}
+ *
+ * @since 2.0
+ */
+ protected String getString(final FileSystemOptions opts, final String name, final String defaultValue)
+ {
+ String value = (String) getParam(opts, name);
+ if (value == null)
+ {
+ value = getProperty(name);
+ if (value == null)
+ {
+ return defaultValue;
+ }
+ }
+ return value;
+ }
+
+ /**
+ * Get the target of this configuration.
+ *
+ * @return the specific file system class
+ *
+ * @since 1.0
+ */
+ protected abstract Class<? extends FileSystem> getConfigClass();
+
+ /**
+ * Converts the given name into a System property key.
+ *
+ * @param name a name to combine with the builder prefix
+ * @return name of system property
+ *
+ * @since 2.1
+ */
+ private String toPropertyKey(final String name)
+ {
+ return this.prefix + name;
+ }
+
+ /**
+ * Get the system property for the given name.
+ *
+ * @param name The name to lookup combined with the prefix.
+ * @return a system property or null
+ *
+ * @since 2.1
+ */
+ private String getProperty(final String name)
+ {
+ return System.getProperty(toPropertyKey(name));
+ }
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileSystemException.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileSystemException.java
new file mode 100644
index 0000000..b1ee6f1
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileSystemException.java
@@ -0,0 +1,196 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+import java.io.IOException;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.apache.commons.vfs2.util.Messages;
+
+/**
+ * Thrown for file system errors.
+ */
+public class FileSystemException
+ extends IOException
+{
+ /**
+ * serialVersionUID format is YYYYMMDD for the date of the last binary change.
+ */
+ private static final long serialVersionUID = 20101208L;
+
+ /** URL pattern */
+ private static final Pattern URL_PATTERN = Pattern.compile("[a-z]+://.*");
+
+ /** Password pattern */
+ private static final Pattern PASSWORD_PATTERN = Pattern.compile(":(?:[^/]+)@");
+
+ /**
+ * Array of complementary info (context).
+ */
+ private final String[] info;
+
+ /**
+ * Constructs exception with the specified detail message.
+ *
+ * @param code the error code of the message.
+ */
+ public FileSystemException(final String code)
+ {
+ this(code, null, (Object[]) null);
+ }
+
+ /**
+ * Constructs exception with the specified detail message.
+ *
+ * @param code the error code of the message.
+ * @param info0 one context information.
+ */
+ public FileSystemException(final String code, final Object info0)
+ {
+ this(code, null, new Object[]{info0});
+ }
+
+ /**
+ * Constructs exception with the specified detail message.
+ *
+ * @param code the error code of the message.
+ * @param info0 one context information.
+ * @param throwable the cause.
+ */
+ public FileSystemException(final String code,
+ final Object info0,
+ final Throwable throwable)
+ {
+ this(code, throwable, new Object[]{info0});
+ }
+
+ /**
+ * Constructs exception with the specified detail message.
+ *
+ * @param code the error code of the message.
+ * @param info array of complementary info (context).
+ */
+ public FileSystemException(final String code, final Object... info)
+ {
+ this(code, null, info);
+ }
+
+ /**
+ * Constructs exception with the specified detail message.
+ *
+ * @param code the error code of the message.
+ * @param throwable the original cause
+ */
+ public FileSystemException(final String code, final Throwable throwable)
+ {
+ this(code, throwable, (Object[]) null);
+ }
+
+ /**
+ * Constructs exception with the specified detail message.
+ *
+ * @param code the error code of the message.
+ * @param info array of complementary info (context).
+ * @param throwable the cause.
+ * @deprecated Use instead {@link #FileSystemException(String, Throwable, Object[])}. Will be removed in 3.0.
+ */
+ @Deprecated
+ public FileSystemException(final String code,
+ final Object[] info,
+ final Throwable throwable)
+ {
+ this(code, throwable, info);
+ }
+
+ /**
+ * Constructs exception with the specified detail message.
+ *
+ * @param code the error code of the message.
+ * @param info array of complementary info (context).
+ * @param throwable the cause.
+ */
+ public FileSystemException(final String code,
+ final Throwable throwable,
+ final Object... info)
+ {
+ super(code, throwable);
+
+ if (info == null)
+ {
+ this.info = new String[0];
+ }
+ else
+ {
+ this.info = new String[info.length];
+ for (int i = 0; i < info.length; i++)
+ {
+ String value = String.valueOf(info[i]);
+ // mask passwords (VFS-169)
+ final Matcher urlMatcher = URL_PATTERN.matcher(value);
+ if (urlMatcher.find())
+ {
+ final Matcher pwdMatcher = PASSWORD_PATTERN.matcher(value);
+ value = pwdMatcher.replaceFirst(":***@");
+ }
+ this.info[i] = value;
+ }
+ }
+ }
+
+ /**
+ * Constructs wrapper exception.
+ *
+ * @param throwable the root cause to wrap.
+ */
+ public FileSystemException(final Throwable throwable)
+ {
+ this(throwable.getMessage(), throwable, (Object[]) null);
+ }
+
+ /**
+ * Retrieves message from bundle.
+ * @return The exception message.
+ */
+ @Override
+ public String getMessage()
+ {
+ return Messages.getString(super.getMessage(), (Object[]) getInfo());
+ }
+
+ /**
+ * Retrieves error code of the exception.
+ * Could be used as key for internationalization.
+ *
+ * @return the code.
+ */
+ public String getCode()
+ {
+ return super.getMessage();
+ }
+
+ /**
+ * Retrieves array of complementary info (context).
+ * Could be used as parameter for internationalization.
+ *
+ * @return the context info.
+ */
+ public String[] getInfo()
+ {
+ return info;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileSystemManager.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileSystemManager.java
new file mode 100644
index 0000000..fa15b70
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileSystemManager.java
@@ -0,0 +1,369 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+import java.io.File;
+import java.lang.reflect.Constructor;
+import java.net.URI;
+import java.net.URL;
+import java.net.URLStreamHandlerFactory;
+import java.util.Collection;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.vfs2.operations.FileOperationProvider;
+
+/**
+ * A FileSystemManager manages a set of file systems. This interface is
+ * used to locate a {@link FileObject} by name from one of those file systems.
+ * <p>
+ * To locate a {@link FileObject}, use one of the {@code resolveFile()}
+ * methods.
+ *
+ * <h2><a name="naming">File Naming</a></h2>
+ *
+ * A file system manager can recognise several types of file names:
+ * <ul>
+ * <li>Absolute URI. These must start with a scheme, such as
+ * {@code file:} or {@code ftp:}, followed by a scheme dependent
+ * file name. Some examples: {@code file:/c:/somefile} or
+ * {@code ftp://somewhere.org/somefile}.</li>
+ * <li>Absolute local file name. For example,
+ * {@code /home/someuser/a-file} or {@code c:\dir\somefile.html}.
+ * Elements in the name can be separated using any of the following
+ * characters: {@code /}, {@code \}, or the native file separator
+ * character. For example, the following file names are the same:
+ * {@code c:\somedir\somefile.xml} and {@code c:/somedir/somefile.xml}.</li>
+ * <li>Relative path. For example: {@code ../somefile} or
+ * {@code somedir/file.txt}. The file system manager resolves relative
+ * paths against its <i>base file</i>. Elements in the relative path can be
+ * separated using {@code /}, {@code \}, or file system specific
+ * separator characters. Relative paths may also contain {@code ..} and
+ * {@code .} elements. See {@link FileObject#resolveFile} for more
+ * details.</li>
+ * </ul>
+ */
+public interface FileSystemManager
+{
+ /**
+ * Returns the base file used to resolve relative paths.
+ *
+ * @return The base FileObject.
+ * @throws FileSystemException if an error occurs.
+ */
+ FileObject getBaseFile() throws FileSystemException;
+
+ /**
+ * Locates a file by name. Equivalent to calling
+ * {@code resolveFile(getBaseFile(), name)}.
+ *
+ * @param name The name of the file.
+ * @return The file. Never returns null.
+ * @throws FileSystemException On error parsing the file name.
+ */
+ FileObject resolveFile(String name) throws FileSystemException;
+
+ /**
+ * Locates a file by name. Equivalent to calling
+ * {@code resolveFile(getBaseFile(), name)}.
+ *
+ * @param name The name of the file.
+ * @param fileSystemOptions The FileSystemOptions used for FileSystem creation.
+ * All files that are later resolved relative to the
+ * returned {@code FileObject} share the options.
+ * @return The file. Never returns null.
+ * @throws FileSystemException On error parsing the file name.
+ */
+ FileObject resolveFile(String name, FileSystemOptions fileSystemOptions)
+ throws FileSystemException;
+
+ /**
+ * Locates a file by name. The name is resolved as described
+ * <a href="#naming">above</a>. That is, the name can be either
+ * an absolute URI, an absolute file name, or a relative path to
+ * be resolved against {@code baseFile}.
+ * <p>
+ * Note that the file does not have to exist when this method is called.
+ *
+ * @param baseFile The base file to use to resolve relative paths.
+ * May be null if the name is an absolute file name.
+ * @param name The name of the file.
+ * @return The file. Never returns null.
+ * @throws FileSystemException On error parsing the file name.
+ */
+ FileObject resolveFile(FileObject baseFile, String name) throws FileSystemException;
+
+ /**
+ * Locates a file by name. See {@link #resolveFile(FileObject, String)}
+ * for details.
+ *
+ * @param baseFile The base file to use to resolve relative paths.
+ * Must not be {@code null}, not even if the <i>name</i> is absolute.
+ * @param name The name of the file.
+ * @return The file. Never returns null.
+ * @throws FileSystemException On error parsing the file name.
+ */
+ FileObject resolveFile(File baseFile, String name) throws FileSystemException;
+
+ /**
+ * Resolves a name, relative to this file name. Equivalent to calling
+ * {@code resolveName( path, NameScope.FILE_SYSTEM )}.
+ *
+ * @param root the base filename
+ * @param name The name to resolve.
+ * @return A {@link FileName} object representing the resolved file name.
+ * @throws FileSystemException If the name is invalid.
+ */
+ FileName resolveName(FileName root, String name) throws FileSystemException;
+
+ /**
+ * Resolves a name, relative to the "root" file name. Refer to {@link NameScope}
+ * for a description of how names are resolved.
+ *
+ * @param root the base filename
+ * @param name The name to resolve.
+ * @param scope The {@link NameScope} to use when resolving the name.
+ * @return A {@link FileName} object representing the resolved file name.
+ * @throws FileSystemException If the name is invalid.
+ */
+ FileName resolveName(FileName root, String name, NameScope scope)
+ throws FileSystemException;
+
+ /**
+ * Converts a local file into a {@link FileObject}.
+ *
+ * @param file The file to convert.
+ * @return The {@link FileObject} that represents the local file. Never
+ * returns null.
+ * @throws FileSystemException On error converting the file.
+ */
+ FileObject toFileObject(File file) throws FileSystemException;
+
+ /**
+ * Creates a layered file system. A layered file system is a file system
+ * that is created from the contents of a file, such as a zip or tar file.
+ *
+ * @param provider The name of the file system provider to use. This name
+ * is the same as the scheme used in URI to identify the provider.
+ * @param file The file to use to create the file system.
+ * @return The root file of the new file system.
+ * @throws FileSystemException On error creating the file system.
+ */
+ FileObject createFileSystem(String provider, FileObject file)
+ throws FileSystemException;
+
+ /**
+ * Closes the given filesystem.
+ * <p>
+ * If you use VFS as singleton it is VERY dangerous to call this method.
+ *
+ * @param filesystem The FileSystem to close.
+ */
+ void closeFileSystem(FileSystem filesystem);
+
+ /**
+ * Creates a layered file system. A layered file system is a file system
+ * that is created from the contents of a file, such as a zip or tar file.
+ *
+ * @param file The file to use to create the file system.
+ * @return The root file of the new file system.
+ * @throws FileSystemException On error creating the file system.
+ */
+ FileObject createFileSystem(FileObject file) throws FileSystemException;
+
+ /**
+ * Creates an empty virtual file system. Can be populated by adding
+ * junctions to it.
+ *
+ * @param rootUri The root URI to use for the new file system. Can be null.
+ * @return The root file of the new file system.
+ * @throws FileSystemException if an error occurs creating the VirtualFileSystem.
+ */
+ FileObject createVirtualFileSystem(String rootUri) throws FileSystemException;
+
+ /**
+ * Creates a virtual file system. The file system will contain a junction
+ * at the fs root to the supplied root file.
+ *
+ * @param rootFile The root file to backs the file system.
+ * @return The root of the new file system.
+ * @throws FileSystemException if an error occurs creating the VirtualFileSystem.
+ */
+ FileObject createVirtualFileSystem(FileObject rootFile) throws FileSystemException;
+
+ /**
+ * Returns a streamhandler factory to enable URL lookup using this
+ * FileSystemManager.
+ *
+ * @return the URLStreamHandlerFactory.
+ */
+ URLStreamHandlerFactory getURLStreamHandlerFactory();
+
+ /**
+ * Determines if a layered file system can be created for a given file.
+ *
+ * @param file The file to check for.
+ * @return true if the FileSystem can be created.
+ * @throws FileSystemException if an error occurs.
+ */
+ boolean canCreateFileSystem(FileObject file) throws FileSystemException;
+
+ /**
+ * Get the cache used to cache fileobjects.
+ *
+ * @return The FilesCache.
+ */
+ FilesCache getFilesCache();
+
+ /**
+ * Get the cache strategy used.
+ *
+ * @return the CacheStrategy.
+ */
+ CacheStrategy getCacheStrategy();
+
+ /**
+ * Get the file object decorator used.
+ *
+ * @return the file object decorator Class.
+ */
+ Class<?> getFileObjectDecorator();
+
+ /**
+ * The constructor associated to the fileObjectDecorator.
+ * We cache it here for performance reasons.
+ *
+ * @return the Constructor associated with the FileObjectDecorator.
+ */
+ Constructor<?> getFileObjectDecoratorConst();
+
+ /**
+ * The class to use to determine the content-type (mime-type).
+ *
+ * @return the FileContentInfoFactory.
+ */
+ FileContentInfoFactory getFileContentInfoFactory();
+
+ /**
+ * Returns true if this manager has a provider for a particular scheme.
+ *
+ * @param scheme The scheme for which a provider should be checked.
+ * @return true if a provider for the scheme is available.
+ */
+ boolean hasProvider(String scheme);
+
+ /**
+ * Get the schemes currently available.
+ *
+ * @return An array of available scheme names that are supported.
+ */
+ String[] getSchemes();
+
+ /**
+ * Get the capabilities for a given scheme.
+ *
+ * @param scheme The scheme to use to locate the provider's capabilities.
+ * @return A Collection of the various capabilities.
+ * @throws FileSystemException if the given scheme is not konwn.
+ */
+ Collection<Capability> getProviderCapabilities(String scheme) throws FileSystemException;
+
+ /**
+ * Sets the logger to use.
+ *
+ * @param log The logger to use.
+ */
+ void setLogger(Log log);
+
+ /**
+ * Get the configuration builder for the given scheme.
+ *
+ * @param scheme The schem to use to obtain the FileSystemConfigBuidler.
+ * @return A FileSystemConfigBuilder appropriate for the given scheme.
+ * @throws FileSystemException if the given scheme is not konwn.
+ */
+ FileSystemConfigBuilder getFileSystemConfigBuilder(String scheme) throws FileSystemException;
+
+ /**
+ * Resolve the uri to a filename.
+ *
+ * @param uri The uri to resolve.
+ * @return A FileName that matches the uri.
+ * @throws FileSystemException if this is not possible.
+ */
+ FileName resolveURI(String uri) throws FileSystemException;
+
+ // -- OPERATIONS --
+ /**
+ * Adds the specified FileOperationProvider for the specified scheme.
+ * <p>
+ * Several FileOperationProvider's might be registered for the same scheme.
+ * For example, for {@code "file"} scheme we can register {@code SvnWsOperationProvider} and
+ * {@code CvsOperationProvider.}
+ *
+ * @param scheme The scheme assoicated with this provider.
+ * @param operationProvider The FileOperationProvider to add.
+ * @throws FileSystemException if an error occurs.
+ */
+ void addOperationProvider(String scheme, FileOperationProvider operationProvider)
+ throws FileSystemException;
+
+ /**
+ * @see FileSystemManager#addOperationProvider(String, org.apache.commons.vfs2.operations.FileOperationProvider)
+ *
+ * @param schemes The schemes that will be associated with the provider.
+ * @param operationProvider The FileOperationProvider to add.
+ * @throws FileSystemException if an error occurs.
+ */
+ void addOperationProvider(String[] schemes, FileOperationProvider operationProvider)
+ throws FileSystemException;
+
+
+ /**
+ * Get Providers for file operations.
+ *
+ * @param scheme the scheme for wich we want to get the list af registered providers.
+ *
+ * @return the registered FileOperationProviders for the specified scheme.
+ * If there were no providers registered for the scheme, it returns null.
+ *
+ * @throws FileSystemException if an error occurs.
+ */
+ FileOperationProvider[] getOperationProviders(String scheme) throws FileSystemException;
+
+ /**
+ * Resolves a URI into a {@link FileObject}.
+ *
+ * @param uri The URI to convert.
+ * @return The {@link FileObject} that represents the URI. Never
+ * returns null.
+ * @throws FileSystemException On error converting the file.
+ * @since 2.1
+ */
+ FileObject resolveFile(URI uri) throws FileSystemException;
+
+ /**
+ * Resolves a URL into a {@link FileObject}.
+ *
+ * @param url The URL to convert.
+ * @return The {@link FileObject} that represents the URL. Never
+ * returns null.
+ * @throws FileSystemException On error converting the file.
+ * @since 2.1
+ */
+ FileObject resolveFile(URL url) throws FileSystemException;
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileSystemOptions.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileSystemOptions.java
new file mode 100644
index 0000000..0f7c945
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileSystemOptions.java
@@ -0,0 +1,264 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.SortedMap;
+import java.util.TreeMap;
+
+/**
+ * Configures file systems individually with these options.
+ * <p>
+ * To configure a file system, you set properties on a {@link FileSystemOptions} object. Most file systems provide a
+ * {@link FileSystemConfigBuilder} with specific options for that file system.
+ * <p>
+ * To use the options, pass them to {@link FileSystemManager#resolveFile(String,FileSystemOptions)}. From there, the
+ * options apply to all files that are resolved relative to that file.
+ *
+ * @see org.apache.commons.vfs2.impl.DefaultFileSystemConfigBuilder
+ * @see org.apache.commons.vfs2.provider.ftp.FtpFileSystemConfigBuilder
+ * @see org.apache.commons.vfs2.provider.ftps.FtpsFileSystemConfigBuilder
+ * @see org.apache.commons.vfs2.provider.hdfs.HdfsFileSystemConfigBuilder
+ * @see org.apache.commons.vfs2.provider.http.HttpFileSystemConfigBuilder
+ * @see org.apache.commons.vfs2.provider.webdav.WebdavFileSystemConfigBuilder
+ * @see org.apache.commons.vfs2.provider.ram.RamFileSystemConfigBuilder
+ * @see org.apache.commons.vfs2.provider.res.ResourceFileSystemConfigBuilder
+ * @see org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder
+ *
+ */
+public final class FileSystemOptions implements Cloneable
+{
+ /** The options */
+ private final Map<FileSystemOptionKey, Object> options;
+
+ /**
+ * Creates a new instance.
+ */
+ public FileSystemOptions()
+ {
+ this(new TreeMap<FileSystemOptionKey, Object>());
+ }
+
+ protected FileSystemOptions(final Map<FileSystemOptionKey, Object> options)
+ {
+ this.options = options;
+ }
+
+ /**
+ * Keys in the options Map.
+ */
+ private static final class FileSystemOptionKey implements Comparable<FileSystemOptionKey>
+ {
+ /** Constant used to create hashcode */
+ private static final int HASH = 29;
+
+ /** The FileSystem class */
+ private final Class<? extends FileSystem> fileSystemClass;
+
+ /** The option name */
+ private final String name;
+
+ // TODO: the parameter name suggests that the class should only be a
+ // a FileSystem, however some of the tests pass in DefaultFileSystemConfigBuilder
+ private FileSystemOptionKey(final Class<? extends FileSystem> fileSystemClass, final String name)
+ {
+ this.fileSystemClass = fileSystemClass;
+ this.name = name;
+ }
+
+ @Override
+ public int compareTo(final FileSystemOptionKey o)
+ {
+ final int ret = fileSystemClass.getName().compareTo(o.fileSystemClass.getName());
+ if (ret != 0)
+ {
+ return ret;
+ }
+ return name.compareTo(o.name);
+ }
+
+ @Override
+ public boolean equals(final Object o)
+ {
+ if (this == o)
+ {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass())
+ {
+ return false;
+ }
+
+ final FileSystemOptionKey that = (FileSystemOptionKey) o;
+
+ if (!fileSystemClass.equals(that.fileSystemClass))
+ {
+ return false;
+ }
+ if (!name.equals(that.name))
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int hashCode()
+ {
+ int result;
+ result = fileSystemClass.hashCode();
+ result = HASH * result + name.hashCode();
+ return result;
+ }
+
+ @Override
+ public String toString()
+ {
+ return fileSystemClass.getName()+"."+name;
+ }
+ }
+
+ void setOption(final Class<? extends FileSystem> fileSystemClass, final String name, final Object value)
+ {
+ options.put(new FileSystemOptionKey(fileSystemClass, name), value);
+ }
+
+ Object getOption(final Class<? extends FileSystem> fileSystemClass, final String name)
+ {
+ final FileSystemOptionKey key = new FileSystemOptionKey(fileSystemClass, name);
+ return options.get(key);
+ }
+
+ boolean hasOption(final Class<? extends FileSystem> fileSystemClass, final String name)
+ {
+ final FileSystemOptionKey key = new FileSystemOptionKey(fileSystemClass, name);
+ return options.containsKey(key);
+ }
+
+ public int compareTo(final FileSystemOptions other)
+ {
+ if (this == other)
+ {
+ // the same instance
+ return 0;
+ }
+
+ final int propsSz = options == null ? 0 : options.size();
+ final int propsFkSz = other.options == null ? 0 : other.options.size();
+ if (propsSz < propsFkSz)
+ {
+ return -1;
+ }
+ if (propsSz > propsFkSz)
+ {
+ return 1;
+ }
+ if (propsSz == 0)
+ {
+ // props empty
+ return 0;
+ }
+
+ // ensure proper sequence of options
+ final SortedMap<FileSystemOptionKey, Object> myOptions =
+ options instanceof SortedMap
+ ? (SortedMap<FileSystemOptionKey, Object>)options
+ : new TreeMap<FileSystemOptionKey, Object>(options);
+ final SortedMap<FileSystemOptionKey, Object> theirOptions =
+ other.options instanceof SortedMap
+ ? (SortedMap<FileSystemOptionKey, Object>)other.options
+ : new TreeMap<FileSystemOptionKey, Object>(other.options);
+ final Iterator<FileSystemOptionKey> optKeysIter = myOptions.keySet().iterator();
+ final Iterator<FileSystemOptionKey> otherKeysIter = theirOptions.keySet().iterator();
+ while(optKeysIter.hasNext()) {
+ int comp = optKeysIter.next().compareTo(otherKeysIter.next());
+ if (comp != 0) {
+ return comp;
+ }
+ }
+
+ Object[] array = new Object[propsSz];
+ final int hash = Arrays.deepHashCode(myOptions.values().toArray(array));
+ final int hashFk = Arrays.deepHashCode(theirOptions.values().toArray(array));
+ if (hash < hashFk)
+ {
+ return -1;
+ }
+ if (hash > hashFk)
+ {
+ return 1;
+ }
+
+ // TODO: compare Entry by Entry ??
+ return 0;
+ }
+
+ @Override
+ public int hashCode()
+ {
+ final int prime = 31;
+ int result = 1;
+ if (options == null) {
+ result = prime * result;
+ } else {
+ final SortedMap<FileSystemOptionKey, Object> myOptions =
+ options instanceof SortedMap
+ ? (SortedMap<FileSystemOptionKey, Object>)options
+ : new TreeMap<FileSystemOptionKey, Object>(options);
+ result = prime * result + myOptions.keySet().hashCode();
+ result = prime * result + Arrays.deepHashCode(myOptions.values().toArray(new Object[options.size()]));
+ }
+ return result;
+ }
+
+ @Override
+ public boolean equals(Object obj)
+ {
+ if (this == obj) {
+ return true;
+ }
+ if (obj == null) {
+ return false;
+ }
+ if (getClass() != obj.getClass()) {
+ return false;
+ }
+ FileSystemOptions other = (FileSystemOptions)obj;
+ return compareTo(other) == 0;
+ }
+
+
+ /**
+ * {@inheritDoc}
+ *
+ * @since 2.0
+ */
+ @Override
+ public Object clone()
+ {
+ return new FileSystemOptions(new TreeMap<FileSystemOptionKey, Object>(options));
+ }
+
+ @Override
+ public String toString()
+ {
+ return options.toString();
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileType.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileType.java
new file mode 100644
index 0000000..922d23e
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileType.java
@@ -0,0 +1,116 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+/**
+ * An enumerated type that represents a file's type.
+ */
+public enum FileType
+{
+ /**
+ * A folder. May contain other files, and have attributes, but does not
+ * have any data content.
+ */
+ FOLDER("folder", true, false, true),
+
+ /**
+ * A regular file. May have data content and attributes, but cannot
+ * contain other files.
+ */
+ FILE("file", false, true, true),
+
+ /**
+ * A file or folder. May have data content and attributes, and can
+ * contain other files.
+ */
+ FILE_OR_FOLDER("fileOrFolder", true, true, true),
+
+ /**
+ * A file that does not exist. May not have data content, attributes,
+ * or contain other files.
+ */
+ IMAGINARY("imaginary", false, false, false);
+
+ /** The name of the FileType */
+ private final String name;
+
+ /** true if the FileType can have children */
+ private final boolean hasChildren;
+
+ /** true if the FileType can have content */
+ private final boolean hasContent;
+
+ /** true if the FileType has attributes */
+ private final boolean hasAttrs;
+
+ private FileType(final String name,
+ final boolean hasChildren,
+ final boolean hasContent,
+ final boolean hasAttrs)
+ {
+ this.name = name;
+ this.hasChildren = hasChildren;
+ this.hasContent = hasContent;
+ this.hasAttrs = hasAttrs;
+ }
+
+ /**
+ * Returns the name of this type.
+ * @return The name of this type.
+ */
+ @Override
+ public String toString()
+ {
+ return name;
+ }
+
+ /**
+ * Returns the name of this type.
+ * @return The name of the type.
+ */
+ public String getName()
+ {
+ return name;
+ }
+
+ /**
+ * Returns true if files of this type may contain other files.
+ * @return true if files can contain other files.
+ */
+ public boolean hasChildren()
+ {
+ return hasChildren;
+ }
+
+ /**
+ * Returns true if files of this type may have data content.
+ * @return true if files can have content.
+ */
+ public boolean hasContent()
+ {
+ return hasContent;
+ }
+
+ /**
+ * Returns true if files of this type may have attributes.
+ * @return true if files can have attributes
+ */
+ public boolean hasAttributes()
+ {
+ return hasAttrs;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileTypeHasNoContentException.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileTypeHasNoContentException.java
new file mode 100644
index 0000000..d4bcba4
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileTypeHasNoContentException.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+/**
+ * delivers a file-not-folder exception which happens when trying to issue
+ * {@link org.apache.commons.vfs2.FileObject#getChildren()} on a file.
+ * @since 2.0
+ */
+public class FileTypeHasNoContentException extends FileSystemException
+{
+ /**
+ * serialVersionUID format is YYYYMMDD for the date of the last binary change.
+ */
+ private static final long serialVersionUID = 20101208L;
+
+ public FileTypeHasNoContentException(final Object info0)
+ {
+ super("vfs.provider/read-not-file.error", info0);
+ }
+
+ public FileTypeHasNoContentException(final Object info0, final Throwable throwable)
+ {
+ super("vfs.provider/read-not-file.error", info0, throwable);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileTypeSelector.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileTypeSelector.java
new file mode 100644
index 0000000..2558589
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileTypeSelector.java
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+/**
+ * A {@link FileSelector} that selects files of a particular type.
+ */
+public class FileTypeSelector
+ implements FileSelector
+{
+ /** The FileType */
+ private final FileType type;
+
+ /**
+ * Creates a new selector for the given file type.
+ *
+ * @param type
+ * The file type to select
+ */
+ public FileTypeSelector(final FileType type)
+ {
+ this.type = type;
+ }
+
+ /**
+ * Determines if a file or folder should be selected.
+ * @param fileInfo The file selection information.
+ * @return true if the file or folder should be selected.
+ * @throws FileSystemException if an error occurs
+ */
+ @Override
+ public boolean includeFile(final FileSelectInfo fileInfo)
+ throws FileSystemException
+ {
+ return fileInfo.getFile().getType() == type;
+ }
+
+ /**
+ * Determines whether a folder should be traversed.
+ * @param fileInfo The file selection information.
+ * @return true if the file or folder should be traversed.
+ */
+ @Override
+ public boolean traverseDescendents(final FileSelectInfo fileInfo)
+ {
+ return true;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FileUtil.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FileUtil.java
new file mode 100644
index 0000000..5b38745
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FileUtil.java
@@ -0,0 +1,93 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+/**
+ * Utility methods for dealing with FileObjects.
+ */
+public final class FileUtil
+{
+
+ private FileUtil()
+ {
+ }
+
+ /**
+ * Returns the content of a file, as a byte array.
+ *
+ * @param file The file to get the content of.
+ * @return The content as a byte array.
+ * @throws IOException if the file content cannot be accessed.
+ */
+ public static byte[] getContent(final FileObject file)
+ throws IOException
+ {
+ final FileContent content = file.getContent();
+ final int size = (int) content.getSize();
+ final byte[] buf = new byte[size];
+
+ final InputStream in = content.getInputStream();
+ try
+ {
+ int read = 0;
+ for (int pos = 0; pos < size && read >= 0; pos += read)
+ {
+ read = in.read(buf, pos, size - pos);
+ }
+ }
+ finally
+ {
+ in.close();
+ }
+
+ return buf;
+ }
+
+ /**
+ * Writes the content of a file to an OutputStream.
+ * @param file The FileObject to write.
+ * @param output The OutputStream to write to.
+ * @throws IOException if an error occurs writing the file.
+ * @see FileContent#write(OutputStream)
+ */
+ public static void writeContent(final FileObject file,
+ final OutputStream output)
+ throws IOException
+ {
+ file.getContent().write(output);
+ }
+
+ /**
+ * Copies the content from a source file to a destination file.
+ * @param srcFile The source FileObject.
+ * @param destFile The target FileObject
+ * @throws IOException If an error occurs copying the file.
+ * @see FileContent#write(FileContent)
+ * @see FileContent#write(FileObject)
+ */
+ public static void copyContent(final FileObject srcFile,
+ final FileObject destFile)
+ throws IOException
+ {
+ srcFile.getContent().write(destFile);
+ }
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/FilesCache.java b/trunk/core/src/main/java/org/apache/commons/vfs2/FilesCache.java
new file mode 100644
index 0000000..113cead
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/FilesCache.java
@@ -0,0 +1,76 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+
+/**
+ * The fileCache interface. Implementations of this interface are expected to be thread safe.
+ */
+public interface FilesCache
+{
+ /**
+ * Adds a FileObject to the cache.
+ *
+ * @param file the file
+ */
+ void putFile(final FileObject file);
+
+ /**
+ * Adds a FileObject to the cache if it isn't already present.
+ *
+ * @param file the file
+ * @return true if the file was stored, false otherwise.
+ */
+ boolean putFileIfAbsent(final FileObject file);
+
+ /**
+ * Retrieves a FileObject from the cache by name.
+ *
+ * @param filesystem The FileSystem.
+ * @param name the name
+ * @return the fileobject or null if file is not cached
+ */
+ FileObject getFile(final FileSystem filesystem, final FileName name);
+
+ /**
+ * Purges the entries corresponding to the FileSystem.
+ *
+ * @param fileSystem The FileSystem.
+ */
+ void clear(final FileSystem fileSystem);
+
+ /**
+ * Purges the whole cache.
+ */
+ void close();
+
+ /**
+ * Removes a file from cache.
+ *
+ * @param filesystem filesystem
+ * @param name filename
+ */
+ void removeFile(final FileSystem filesystem, final FileName name);
+
+ /**
+ * If the cache uses timestamps it could use this method to handle
+ * updates of them.
+ *
+ * @param file filename
+ */
+ // public void touchFile(final FileObject file);
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/NameScope.java b/trunk/core/src/main/java/org/apache/commons/vfs2/NameScope.java
new file mode 100644
index 0000000..8b43e53
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/NameScope.java
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+/**
+ * An enumerated type for file name scope, used when resolving a name relative
+ * to a file.
+ */
+public enum NameScope
+{
+ /**
+ * Resolve against the children of the base file. The name is resolved
+ * as described by {@link #FILE_SYSTEM}. However, an exception is
+ * thrown if the resolved file is not a direct child of the base file.
+ */
+ CHILD("child"),
+
+ /**
+ * Resolve against the descendants of the base file. The name is resolved
+ * as described by {@link #FILE_SYSTEM}. However, an exception is thrown
+ * if the resolved file is not a descendent of the base file.
+ */
+ DESCENDENT("descendent"),
+
+ /**
+ * Resolve against the descendants of the base file. The name is resolved
+ * as described by {@link #FILE_SYSTEM}. However, an exception is thrown
+ * if the resolved file is not a descendent of the base file, or the base
+ * files itself.
+ */
+ DESCENDENT_OR_SELF("descendent_or_self"),
+
+ /**
+ * Resolve against files in the same file system as the base file.
+ * <p>
+ * If the supplied name is an absolute path, then it is resolved
+ * relative to the root of the file system that the base file belongs to.
+ * If a relative name is supplied, then it is resolved relative to the base
+ * file.
+ * <p>
+ * The path may use any mix of {@code /}, {@code \}, or file
+ * system specific separators to separate elements in the path. It may
+ * also contain {@code .} and {@code ..} elements.
+ * <p>
+ * A path is considered absolute if it starts with a separator character,
+ * and relative if it does not.
+ */
+ FILE_SYSTEM("filesystem");
+
+ /** The name */
+ private final String realName;
+
+ private NameScope(final String name)
+ {
+ this.realName = name;
+ }
+
+ /**
+ * Returns the name of the scope.
+ * @return The name of the scope.
+ */
+ @Override
+ public String toString()
+ {
+ return realName;
+ }
+
+ /**
+ * Returns the name of the scope.
+ * @return The name of the scope.
+ */
+ public String getName()
+ {
+ return realName;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/PatternFileSelector.java b/trunk/core/src/main/java/org/apache/commons/vfs2/PatternFileSelector.java
new file mode 100644
index 0000000..b78d4bb
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/PatternFileSelector.java
@@ -0,0 +1,103 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+import java.util.regex.Pattern;
+
+/**
+ * A {@link FileSelector} that selects based on regular expressions matched against base filename.
+ *
+ * @since 2.1
+ */
+public class PatternFileSelector implements FileSelector
+{
+
+ /**
+ * The extensions to select.
+ */
+ private final Pattern pattern;
+
+ /**
+ * Creates a new selector for the given pattern.
+ *
+ * @param pattern
+ * The regular expressed used by this selector.
+ */
+ public PatternFileSelector(final Pattern pattern)
+ {
+ this.pattern = pattern;
+ }
+
+ /**
+ * Creates a new selector for the given pattern.
+ *
+ * @param regex
+ * The regular expressed used by this selector.
+ */
+ public PatternFileSelector(final String regex)
+ {
+ this(Pattern.compile(regex));
+ }
+
+ /**
+ * Creates a new selector for the given Pattern and flags.
+ *
+ * @param regex
+ * The expression to be compiled
+ *
+ * @param flags
+ * Match flags, a bit mask.
+ *
+ * @see Pattern#compile(String, int)
+ */
+ public PatternFileSelector(final String regex, final int flags)
+ {
+ this(Pattern.compile(regex, flags));
+ }
+
+ /**
+ * Determines if a file or folder should be selected.
+ *
+ * @param fileInfo
+ * The file selection information.
+ * @return true if the file should be selected, false otherwise.
+ */
+ @Override
+ public boolean includeFile(final FileSelectInfo fileInfo)
+ {
+ return this.pattern.matcher(fileInfo.getFile().getName().getPath()).matches();
+ }
+
+ @Override
+ public String toString()
+ {
+ return this.pattern.toString();
+ }
+
+ /**
+ * Determines whether a folder should be traversed.
+ *
+ * @param fileInfo
+ * The file selection information.
+ * @return true if descendants should be traversed, false otherwise.
+ */
+ @Override
+ public boolean traverseDescendents(final FileSelectInfo fileInfo)
+ {
+ return true;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/RandomAccessContent.java b/trunk/core/src/main/java/org/apache/commons/vfs2/RandomAccessContent.java
new file mode 100644
index 0000000..a52b352
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/RandomAccessContent.java
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+ * Provides random access over content.
+ */
+public interface RandomAccessContent extends DataOutput, DataInput
+{
+ /**
+ * Closes this random access file stream and releases any system resources associated with the stream.
+ * <p>
+ * A closed random access file cannot perform input or output operations and cannot be reopened.
+ * </p>
+ * <p>
+ * If this file has an associated channel then the channel is closed as well.
+ * <p>
+ *
+ * @throws IOException
+ * if an I/O error occurs.
+ */
+ void close() throws IOException;
+
+ /**
+ * Returns the current offset in this file.
+ *
+ * @return the offset from the beginning of the file, in bytes, at which the next read or write occurs.
+ * @throws IOException
+ * if an I/O error occurs.
+ */
+ long getFilePointer() throws IOException;
+
+ /**
+ * Get the input stream.
+ * <p>
+ * <b>Notice: If you use {@link #seek(long)} you have to re-get the InputStream</b>
+ * </p>
+ *
+ * @return the InputStream.
+ * @throws IOException
+ * if an I/O error occurs.
+ */
+ InputStream getInputStream() throws IOException;
+
+ /**
+ * Returns the length of this file.
+ *
+ * @return the length of this file, measured in bytes.
+ * @throws IOException
+ * if an I/O error occurs.
+ */
+ long length() throws IOException;
+
+ /**
+ * Sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.
+ * <p>
+ * The offset may be set beyond the end of the file. Setting the offset beyond the end of the file does not change
+ * the file length. The file length will change only by writing after the offset has been set beyond the end of the
+ * file.
+ * </p>
+ * <p>
+ * <b>Notice: If you use {@link #getInputStream()} you have to re-get the InputStream after calling
+ * {@link #seek(long)}</b>
+ * </p>
+ *
+ * @param pos
+ * the offset position, measured in bytes from the beginning of the file, at which to set the file
+ * pointer.
+ * @throws IOException
+ * if {@code pos} is less than {@code 0} or if an I/O error occurs.
+ */
+ void seek(long pos) throws IOException;
+
+ /**
+ * Sets the length of this content.
+ *
+ * <p>
+ * If the the {@code newLength} argument is smaller than {@link #length()}, the content is truncated.
+ * </p>
+ *
+ * <p>
+ * If the the {@code newLength} argument is greater than {@link #length()}, the content grows with undefined data.
+ * </p>
+ *
+ * @param newLength
+ * The desired content length
+ * @exception IOException
+ * If an I/O error occurs
+ * @since 2.1
+ */
+ void setLength(long newLength) throws IOException;
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/Resources.properties b/trunk/core/src/main/java/org/apache/commons/vfs2/Resources.properties
new file mode 100644
index 0000000..34270b9
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/Resources.properties
@@ -0,0 +1,301 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# $Id$
+
+# Factory
+vfs/create-manager.error=Could not create a file system manager of class "{0}".
+
+# AbstractFileObject
+vfs.provider/delete-not-supported.error=This file type does not support delete.
+vfs.provider/rename-not-supported.error=This file type does not support rename.
+vfs.provider/write-append-not-supported.error=The file type does not support append mode.
+vfs.provider/random-access-not-supported.error=The file type does not support random access.
+vfs.provider/random-access-read-not-supported.error=The file type does not support read in random access mode.
+vfs.provider/random-access-write-not-supported.error=The file type does not support write in random access mode.
+vfs.provider/create-folder-not-supported.error=This file type does not support folder creation.
+vfs.provider/get-last-modified-not-supported.error=This file type does not support retriving last modified time.
+vfs.provider/set-last-modified-not-supported.error=This file type does not support setting last modified time.
+vfs.provider/set-attribute-not-supported.error=This file type does not support setting attributes.
+vfs.provider/remove-attribute-not-supported.error=This file type does not support removing attributes.
+vfs.provider/get-attribute-not-supported.error=This file type does not support getting attributes.
+vfs.provider/write-not-supported.error=This file type cannot be written to.
+vfs.provider/get-type.error=Could not determine the type of file "{0}".
+vfs.provider/list-children-not-folder.error=Could not list the contents of "{0}" because it is not a folder.
+vfs.provider/list-children.error=Could not list the contents of folder "{0}".
+vfs.provider/delete-read-only.error=Could not delete "{0}" because it is read-only.
+vfs.provider/rename-read-only.error=Could not rename "{0}" because it is read-only.
+vfs.provider/rename-parent-read-only.error=Could not rename "{0}" because "{1}" is read-only.
+vfs.provider/rename-dest-exists.error=Destination "{0}" already existent.
+vfs.provider/delete.error=Could not delete "{0}".
+vfs.provider/rename.error=Could not rename "{0}" to "{1}".
+vfs.provider/create-folder-mismatched-type.error=Could not create folder "{0}" because it already exists and is a file.
+vfs.provider/create-folder-read-only.error=Could not create folder "{0}" because its parent folder is read-only.
+vfs.provider/create-folder.error=Could not create folder "{0}".
+vfs.provider/create-file.error=Could not create file "{0}".
+vfs.provider/write-read-only.error=Could not write to "{0}" because it is read-only.
+vfs.provider/write-not-file.error=Could not write to "{0}" because it is not a file.
+vfs.provider/write.error=Could not write to "{0}".
+vfs.provider/copy-file.error=Could not copy "{0}" to "{1}".
+vfs.provider/rename-filename.error=You can only rename within the same folder. Invalid Filename: "{0}".
+vfs.provider/copy-read-only.error=Could not copy {0} "{1}" to "{2}" because the destination file is read-only.
+vfs.provider/copy-missing-file.error=Could not copy "{0}" because it does not exist.
+vfs.provider/find-files.error=Could not find files in "{0}".
+vfs.provider/check-is-executable.error=Could not determine if file "{0}" is executable.
+vfs.provider/check-is-hidden.error=Could not determine if file "{0}" is hidden.
+vfs.provider/check-is-writeable.error=Could not determine if file "{0}" is writeable.
+vfs.provider/check-is-readable.error=Could not determine if file "{0}" is readable.
+vfs.provider/set-executable.error=Could not set the executable flag of file "{0}".
+vfs.provider/set-writeable.error=Could not set the writeable flag of file "{0}".
+vfs.provider/set-readable.error=Could not set the readable flag of file "{0}".
+vfs.provider/get-url.error=Could not create URL for "{0}".
+vfs.provider/resync.error=Could not resync "{0}".
+vfs.provider/close.error=Could not close "{0}".
+vfs.provider/read.error=Could not read file "{0}".
+vfs.provider/random-access.error=Could not read/write file "{0}".
+vfs.provider/read-not-readable.error=File "{0}" is not readable.
+vfs.provider/read-not-file.error=Could not read from "{0}" because it is not a file.
+vfs.provider/closed.error=File closed.
+
+# DefaultFileContent
+vfs.provider/get-size-not-file.error=Could not determine the size of "{0}" because it is not a file.
+vfs.provider/get-size-write.error=Could not determine the size of file "{0}" because it is being written to.
+vfs.provider/get-size.error=Could not determine the size of file "{0}".
+vfs.provider/read-in-use.error=Could not read file "{0}" because it is currently being written to.
+vfs.provider/write-in-use.error=Could not write to "{0}" because it is currently in use.
+vfs.provider/random-in-use.error=Could not read/write file "{0}" because it is currently in use.
+vfs.provider/get-last-modified-writing.error=Could not determine the last modified timestamp of "{0}" because it is being written to.
+vfs.provider/get-last-modified-no-exist.error=Could not determine the last modified timestamp of "{0}" because it does not exist.
+vfs.provider/get-last-modified.error=Could not determine the last modified timestamp of "{0}".
+vfs.provider/set-last-modified-writing.error=Could not set the last modified timestamp of "{0}" because it is being written to.
+vfs.provider/set-last-modified-no-exist.error=Could not set the last modified timestamp of "{0}" because it does not exist.
+vfs.provider/set-last-modified.error=Could not set the last modified timestamp of "{0}".
+vfs.provider/get-certificates-no-exist.error=Could not retrieve the certificates of "{0}" because it does not exist.
+vfs.provider/get-certificates-writing.error=Could not retrieve the certificates of "{0}" because it is being written to.
+vfs.provider/get-certificates.error=Could not retrieve the certificates of "{0}".
+vfs.provider/close-instr.error=Could not close the input stream for file "{0}".
+vfs.provider/close-outstr.error=Could not close the output stream for file "{0}".
+vfs.provider/close-rac.error=Could not close the random access content for file "{0}".
+vfs.provider/exists-attribute-no-exist.error=Could not check if attribute "{0}" of "{1}" exists because attributes are not supported.
+vfs.provider/get-attributes-no-exist.error=Could not get attributes for file "{0}" because it does not exist.
+vfs.provider/get-attributes.error=Could not get attributes "{0}".
+vfs.provider/set-attribute-no-exist.error=Could not set attribute "{0}" of "{1}" because it does not exist.
+vfs.provider/set-attribute.error=Could not set attribute "{0}" of "{1}".
+vfs.provider/remove-attribute-no-exist.error=Could not check if attribute "{0}" of "{1}" exists because attributes are not supported.
+vfs.provider/remove-attribute.error=Could not remove attribute "{0}" of "{1}".
+
+# AbstractFileSystemProvider
+vfs.provider/invalid-absolute-uri.error=Invalid absolute URI "{0}".
+vfs.provider/not-layered-fs.error=File system for URL scheme "{0}" is not a layered file system.
+vfs.provider/no-config-builder.error=File provider for URL scheme "{0}" does not provide a configuration builder.
+vfs.provider/config-key-invalid.error=The configuration builder for scheme "{0}" has no option "{1}".
+vfs.provider/config-value-invalid.error=The delegating configuration builder cant convert value "{2}" for key "{1}" scheme "{0}".
+vfs.provider/config-too-many-values.error=Too many values for configuration builder for scheme "{0}" key "{1}".
+vfs.provider/config-unexpected-primitive.error=Unexpected primitive "{0}".
+vfs.provider/config-unexpected-value-class.error=Cant convert a "{0}" value for scheme "{1}" key "{2}".
+
+# AbstractFileSystem
+vfs.provider/files-cache-missing.error=No files-cache implementation set.
+vfs.provider/mismatched-fs-for-name.error=Incorrect file system URI "{2}" in name "{0}", was expecting "{1}".
+vfs.provider/junctions-not-supported.error=Junctions not supported for file system "{0}".
+vfs.provider/notify-listener.warn=Could not notify listener of change to "{0}".
+vfs.provider/replicate-missing-file.error=Could not replicate "{0}" as it does not exist.
+vfs.provider/replicate-file.error=Could not replicate "{0}".
+vfs.provider/resolve-file.error=Could not resolve file "{0}".
+
+# AbstractFileProvider
+vfs.provider/filename-parser-missing.error=No filename-parser implementation set.
+
+# AbstractFileName
+vfs.provider/filename-type.error=A filename can only be of type FileType.FOLDER or FileType.FILE
+
+# Operations
+vfs.operation/wrong-type.error=Can't lookup operation, wrong type: "{0}"
+vfs.operation/not-found.error=Operation not found, type: "{0}"
+vfs.operation/cant-register.error=Can't register operation, wrong type: "{0}"
+vfs.operation/operation-not-supported.error=Operation "{0}" not supported.
+vfs.operation/operation-provider-already-added.error=Operation provider already added to scheme "{0}"
+
+# RandomAccess
+vfs.provider/random-access-invalid-position.error=Invalid position: "{0}"
+vfs.provider/random-access-open-failed.error=Could not access file "{0}" because it does not exist.
+
+# UriParser
+vfs.provider/missing-double-slashes.error=Expecting // to follow the scheme in URI "{0}".
+vfs.provider/missing-hostname.error=Hostname missing from URI "{0}".
+vfs.provider/missing-port.error=Port number is missing from URI "{0}".
+vfs.provider/missing-hostname-path-sep.error=Expecting / to follow the hostname in URI "{0}".
+vfs.provider/invalid-descendent-name.error=Invalid descendent file name "{0}".
+vfs.provider/invalid-escape-sequence.error=Invalid URI escape sequence "{0}".
+vfs.provider/invalid-relative-path.error=Invalid relative file name.
+
+# DefaultFileSystemManager
+vfs.impl/unknown-scheme.error=Unknown scheme "{0}" in URI "{1}".
+vfs.impl/find-rel-file.error=Could not find file with URI "{0}" because it is a relative path, and no base URI was provided.
+vfs.impl/multiple-providers-for-scheme.error=Multiple providers registered for URL scheme "{0}".
+vfs.impl/configuration-already-set.error=FilesCache implementation already set.
+vfs.impl/configuration-already-in-use.error=The configuration is already attached to an filesystemmanager. You cant change it anymore.
+vfs.impl/unknown-provider.error=No file provider is registered with URI scheme "{0}" to handle file "{1}".
+vfs.impl/no-provider-for-file.error=Could not find a file provider that can handle file "{0}".
+vfs.impl/no-local-file-provider.error=Could not find a file provider which can handle local files.
+vfs.impl/no-replicator.error=No file replicator configured.
+vfs.impl/no-temp-file-store.error=No temporary file store configured.
+vfs.impl/replicate-file.error=Could not replicate "{0}".
+vfs.impl/delete-temp.warn=Could not clean up temporary file "{0}".
+vfs.impl/init-replicator.error=Could not initialise file replicator.
+vfs.impl/already-inited.error=Manager already inited, cant change the configuration now.
+vfs.impl/invalid-decorator.error="{0}" is not a valid decorator. It has to extend "DecoratedFileObject" and must provide a single argument constructor which takes a "FileObject"
+vfs.impl/temp-dir.info=Using "{0}" as temporary files store.
+
+# StandardFileSystemManager
+vfs.impl/find-config-file.error=Could not find VFS configuration resource "{0}".
+vfs.impl/load-config.error=Could not load VFS configuration from "{0}".
+vfs.impl/create-provider.error=Could not create file provider of class "{0}".
+vfs.impl/create-files-cache.error=Could not create files-cache implementation of class "{0}".
+vfs.impl/create-client-factory.error=Could not create client factory of class "{0}".
+vfs.impl/skipping-provider.debug=Skipping provider "{0}" because required class "{1}" is not available.
+vfs.impl/skipping-provider-scheme.debug=Skipping provider "{0}" because required scheme "{1}" is not available.
+
+# FileTypeMap
+vfs.impl/multiple-schemes.error=This file requires multiple schemes. Use getSchemes() instead.
+
+# VFSClassLoader
+vfs.impl/pkg-sealing-unsealed=Trying to seal package "{0}" that exists as unsealed.
+vfs.impl/pkg-sealed-other-url=Package "{0}" exists and is sealed with other URL.
+
+# VirtualFileSystem
+vfs.impl/nested-junction.error=Attempting to create a nested junction at "{0}". Nested junctions are not supported.
+vfs.impl/create-junction.error=Could not create a junction at "{0}".
+
+# SoftRefFilesCache
+vfs.impl/SoftRefReleaseThread-interrupt.info=SoftRefFilesCache - Release Thread interrupted.
+vfs.impl/SoftRefReleaseThread-already-running.warn=SoftRefFilesCache - Release Thread already running.
+
+# Local Provider
+vfs.provider.local/get-type.error=Could not determine the type of "{0}".
+vfs.provider.local/delete-file.error=Could not delete "{0}".
+vfs.provider.local/rename-file.error=Could not rename file "{0}" to "{1}".
+vfs.provider.local/create-folder.error=Could not create directory "{0}".
+vfs.provider.local/not-absolute-file-name.error=URI "{0}" is not an absolute file name.
+vfs.provider.local/missing-share-name.error=Share name missing from UNC file name "{0}".
+
+# Temp Provider
+vfs.provider.temp/get-type.error=Could not determine the type of "{0}".
+vfs.provider.temp/delete-file.error=Could not delete "{0}".
+vfs.provider.temp/rename-file.error=Could not rename file "{0}" to "{1}".
+vfs.provider.temp/create-folder.error=Could not create directory "{0}".
+vfs.provider.temp/not-absolute-file-name.error=URI "{0}" is not an absolute file name.
+vfs.provider.temp/missing-share-name.error=Share name missing from UNC file name "{0}".
+
+# SMB Provider
+vfs.provider.smb/missing-share-name.error=The share name is missing from URI "{0}".
+vfs.provider.smb/get-type.error=Could not detemine the type of "{0}".
+
+# Zip Provider
+vfs.provider.zip/open-zip-file.error=Could not open Zip file "{0}".
+vfs.provider.zip/close-zip-file.error=Could not close Zip file "{0}".
+
+# Bzip2 Provider
+vfs.provider.bzip2/not-a-bzip2-file.error=File "{0}" is not bzip2 compressed.
+
+# JarFileSystem
+vfs.provider.jar/open-jar-file.error=Could not open Jar file "{0}".
+
+# JarURLConnectionImpl
+vfs.provider.jar/jar-file-no-access.error=JarURLConnections in VFS does not give access to the JarFile.
+vfs.provider.jar/jar-entry-no-access.error=JarURLConnections in VFS does not give access to the JarEntry.
+
+# FTP Provider
+vfs.provider.ftp.wrapper/change-work-directory-back.error=Could not change back to work directory "{0}".
+vfs.provider.ftp/change-work-directory.error=Could not change to work directory "{0}".
+vfs.provider.ftp/close-connection.error=Could not close connection to FTP server.
+vfs.provider.ftp/connect-rejected.error=Connection to FTP server on "{0}" rejected.
+vfs.provider.ftp/connect.error=Could not connect to FTP server on "{0}".
+vfs.provider.ftp/create-folder.error=Could not create FTP directory "{0}".
+vfs.provider.ftp/delete-file.error=Could not delete FTP file "{0}".
+vfs.provider.ftp/finish-get.error=Could not get FTP file "{0}".
+vfs.provider.ftp/finish-put.error=Could not put FTP file "{0}".
+vfs.provider.ftp/get-type.error=Could not determine the file type of "{0}".
+vfs.provider.ftp/input-error.debug=Cant open input connection for file "{0}". Reason: "{1}".
+vfs.provider.ftp/invalid-directory-entry.debug=Invalid directory entry at line "{0}" (directory "{1}").
+vfs.provider.ftp/login.error=Could not login to FTP server on "{0}" as user "{1}".
+vfs.provider.ftp/output-error.debug=Cant open output connection for file "{0}". Reason: "{1}".
+vfs.provider.ftp/rename-file.error=Could not rename FTP file "{0}" to "{1}".
+vfs.provider.ftp/set-file-type.error=Could not set the file type to "{0}".
+
+# FTPS Provider
+vfs.provider.ftps/data-channel.level=Failed to setup secure data channel level "{0}".
+
+# SFTP Provider
+vfs.provider.sftp/change-work-directory-back.error=Could not change back to work directory "{0}".
+vfs.provider.sftp/change-work-directory.error=Could not change to work directory "{0}".
+vfs.provider.sftp/config-sshdir.error=SSH-Folder "{0}" non existent or not a folder.
+vfs.provider.sftp/connect.error=Could not connect to SFTP server at "{0}".
+vfs.provider.sftp/create-folder.error=Folder creation failed with unknown error.
+vfs.provider.sftp/delete.error=Delete failed with unknown error.
+vfs.provider.sftp/filename-encoding.error=Could not change to file name encoding "{0}"
+vfs.provider.sftp/get-file.error=Read file contents failed with unknown error.
+vfs.provider.sftp/known-hosts.error=Error during processing known-hosts file "{0}".
+vfs.provider.sftp/list-children.error=List folder contents failed with unknown error.
+vfs.provider.sftp/load-private-key.error=Could not load private key from "{0}".
+vfs.provider.sftp/put-file.error=Write file contents failed with unknown error.
+vfs.provider.sftp/StrictHostKeyChecking-arg.error=Illegal argument "{0}" hostKeyChecking can only be "ask", "yes" or "no"
+vfs.provider.sftp/unknown-modtime.error=Last modification time not fetched.
+vfs.provider.sftp/unknown-permissions.error=File permissions not fetched.
+vfs.provider.sftp/unknown-size.error=File size not fetched.
+
+# URL Provider
+vfs.provider.url/badly-formed-uri.error=Badly formed URI "{0}".
+
+# Http Provider
+vfs.provider.http/get.error=GET method failed for "{0}" with HTTP status {1}.
+vfs.provider.http/head.error=HEAD method failed for "{0}" with HTTP status {1}.
+vfs.provider.http/last-modified.error=No Last-Modified header in HTTP response.
+vfs.provider.http/get-range.error=GET method failed for "{0}" range "{1}" with HTTP status {2}.
+vfs.provider.http/connect.error=Could not connect to HTTP server on "{0}".
+
+# WebDAV Provider
+vfs.provider.webdav/write-file.error=Write to file failed with message: "{0}".
+vfs.provider.webdav/list-children.error=List child resources failed with message: "{0}".
+vfs.provider.webdav/create-collection.error=Create collection failed with message: "{0}".
+vfs.provider.webdav/delete-file.error=Delete file failed with message: "{0}".
+vfs.provider.webdav/create-client.error=Could not create client for server "{0}".
+vfs.provider.webdav/rename-file.error=Rename file failed with message: "{0}".
+vfs.provider.webdav/get-attributes.error=Could not get attributes for: "{0}".
+vfs.provider.webdav/set-attributes.error=Could not set property "{1}" for: "{0}".
+vfs.provider.webdav/get-property.error=Could not get property for: "{0}", name="{1}", type="{2}", nameSet="{3}", addEncoding="{4}".
+
+# Tar
+vfs.provider.tar/open-tar-file.error=Could not open Tar file "{0}".
+vfs.provider.tar/close-tar-file.error=Could not close Tar file "{0}".
+
+# Ant tasks
+vfs.tasks/sync.no-destination.error=No destination file or directory specified.
+vfs.tasks/sync.too-many-destinations.error=Cannot specify both a destination file and a destination directory.
+vfs.tasks/sync.no-source-files.warn=No source files specified.
+vfs.tasks/sync.no-source-file.error=No source file specified.
+vfs.tasks/sync.too-many-source-files.error=Too many source files specified.
+vfs.tasks/sync.source-not-file.error=Source file "{0}" is not a file, or does not exist.
+vfs.tasks/sync.src-file-no-exist.warn=Source file "{0}" does not exist.
+vfs.tasks/sync.duplicate-source-files.warn=Multiple source files for destination file "{0}".
+vfs.tasks/delete.no-source-files.error=No files to delete specified.
+vfs.tasks/mkdir.create-folder.info=Creating directory "{0}".
+
+# Selectors
+vfs.selectors/filefilter.missing.error=Configure a fileFilter or override accept().
+
+# Utils
+vfs.util/find-abstract-file-object.error=Object "{0}" did not extend from AbstractFileObject.
+vfs.util/missing-capability.error=The Filesystem does not provide the required capability "{0}".
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/Selectors.java b/trunk/core/src/main/java/org/apache/commons/vfs2/Selectors.java
new file mode 100644
index 0000000..1d539fc
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/Selectors.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+/**
+ * Several standard file selectors.
+ */
+public final class Selectors
+{
+ /**
+ * A {@link FileSelector} that selects only the base file/folder.
+ */
+ public static final FileSelector SELECT_SELF = new FileDepthSelector();
+
+ /**
+ * A {@link FileSelector} that selects the base file/folder and its
+ * direct children.
+ */
+ public static final FileSelector SELECT_SELF_AND_CHILDREN = new FileDepthSelector(0, 1);
+
+ /**
+ * A {@link FileSelector} that selects only the direct children
+ * of the base folder.
+ */
+ public static final FileSelector SELECT_CHILDREN = new FileDepthSelector(1);
+
+ /**
+ * A {@link FileSelector} that selects all the descendants of the
+ * base folder, but does not select the base folder itself.
+ */
+ public static final FileSelector EXCLUDE_SELF = new FileDepthSelector(1, Integer.MAX_VALUE);
+
+ /**
+ * A {@link FileSelector} that only files (not folders).
+ */
+ public static final FileSelector SELECT_FILES = new FileTypeSelector(FileType.FILE);
+
+ /**
+ * A {@link FileSelector} that only folders (not files).
+ */
+ public static final FileSelector SELECT_FOLDERS = new FileTypeSelector(FileType.FOLDER);
+
+ /**
+ * A {@link FileSelector} that selects the base file/folder, plus all
+ * its descendants.
+ */
+ public static final FileSelector SELECT_ALL = new AllFileSelector();
+
+ /**
+ * Prevent the class from being instantiated.
+ */
+ private Selectors()
+ {
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/UserAuthenticationData.java b/trunk/core/src/main/java/org/apache/commons/vfs2/UserAuthenticationData.java
new file mode 100644
index 0000000..f35a381
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/UserAuthenticationData.java
@@ -0,0 +1,158 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+import java.util.Iterator;
+import java.util.Map;
+import java.util.TreeMap;
+
+/**
+ * Contains various authentication data.
+ */
+public class UserAuthenticationData
+{
+ /**
+ * Represents a user authentication item.
+ */
+ public static class Type implements Comparable<Type>
+ {
+ /** The type name */
+ private final String type;
+
+ /**
+ * Creates a new Type.
+ *
+ * @param type the type
+ */
+ public Type(final String type)
+ {
+ this.type = type;
+ }
+
+ @Override
+ public boolean equals(final Object o)
+ {
+ if (this == o)
+ {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass())
+ {
+ return false;
+ }
+
+ final Type type1 = (Type) o;
+
+ if (type != null ? !type.equals(type1.type) : type1.type != null)
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ @Override
+ public int compareTo(final Type o)
+ {
+ return type.compareTo(o.type);
+ }
+
+ /**
+ * @return The hash code.
+ * @since 2.0
+ * */
+ @Override
+ public int hashCode()
+ {
+ return type != null ? type.hashCode() : 0;
+ }
+
+ /**
+ * @return The type.
+ * @since 2.0
+ * */
+ @Override
+ public String toString()
+ {
+ return type;
+ }
+ }
+
+ /** The user name. */
+ public static final Type USERNAME = new Type("username");
+
+ /** The password. */
+ public static final Type PASSWORD = new Type("password");
+
+ /** The user's domain. */
+ public static final Type DOMAIN = new Type("domain");
+
+ /** The authentication data. */
+ private final Map<Type, char[]> authenticationData = new TreeMap<Type, char[]>();
+
+ /**
+ * Creates a new uninitialized instance.
+ */
+ public UserAuthenticationData()
+ {
+ // do nothing
+ }
+
+ /**
+ * Sets a data to this collection.
+ * @param type The Type to add
+ * @param data The data associated with the Type
+ */
+ public void setData(final Type type, final char[] data)
+ {
+ authenticationData.put(type, data);
+ }
+
+ /**
+ * Gets a data from the collection.
+ * @param type The Type to retrieve.
+ * @return a character array containing the data associated with the type.
+ */
+ public char[] getData(final Type type)
+ {
+ return authenticationData.get(type);
+ }
+
+ /**
+ * Deletes all data stored within this authenticator.
+ */
+ public void cleanup()
+ {
+ // step 1: nullify character buffers
+ final Iterator<char[]> iterAuthenticationData = authenticationData.values().iterator();
+ while (iterAuthenticationData.hasNext())
+ {
+ final char[] data = iterAuthenticationData.next();
+ if (data == null || data.length < 0)
+ {
+ continue;
+ }
+
+ for (int i = 0; i < data.length; i++)
+ {
+ data[i] = 0;
+ }
+ }
+ // step 2: allow data itself to gc
+ authenticationData.clear();
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/UserAuthenticator.java b/trunk/core/src/main/java/org/apache/commons/vfs2/UserAuthenticator.java
new file mode 100644
index 0000000..9885986
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/UserAuthenticator.java
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+/**
+ * The user authenticator is used to query credentials from the user. Since a UserAuthenticator
+ * is provided with the {@link FileSystemOptions} to a {@link FileSystem} it should also implement
+ * reasonable equals and hashCode functions if the FileSystem should be shared.
+ */
+public interface UserAuthenticator
+{
+ /**
+ * Queries the given type from the user.
+ * @param types An array containing the user's credentials
+ * @return The UserAuthenticationData.
+ */
+ UserAuthenticationData requestAuthentication(UserAuthenticationData.Type[] types);
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/VFS.java b/trunk/core/src/main/java/org/apache/commons/vfs2/VFS.java
new file mode 100644
index 0000000..4a06105
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/VFS.java
@@ -0,0 +1,116 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+
+/**
+ * The main entry point for the VFS. Used to create {@link FileSystemManager}
+ * instances.
+ */
+public final class VFS
+{
+ /** The URI style */
+ private static Boolean uriStyle;
+
+ /** The FileSystemManager */
+ private static FileSystemManager instance;
+
+ private VFS()
+ {
+ }
+
+ /**
+ * Returns the default {@link FileSystemManager} instance.
+ * <p>
+ * Warning, if you close this instance you may affect all current
+ * and future users of this manager singleton.
+ *
+ * @return The FileSystemManager.
+ * @throws FileSystemException if an error occurs creating the manager.
+ */
+ public static synchronized FileSystemManager getManager()
+ throws FileSystemException
+ {
+ if (instance == null)
+ {
+ instance = createManager("org.apache.commons.vfs2.impl.StandardFileSystemManager");
+ }
+ return instance;
+ }
+
+ /**
+ * Creates a file system manager instance.
+ * @param managerClassName The specific manager impelmentation class name.
+ * @return The FileSystemManager.
+ * @throws FileSystemException if an error occurs creating the manager.
+ */
+ private static FileSystemManager createManager(final String managerClassName)
+ throws FileSystemException
+ {
+ try
+ {
+ // Create instance
+ final Class<?> mgrClass = Class.forName(managerClassName);
+ final FileSystemManager mgr = (FileSystemManager) mgrClass.newInstance();
+
+ try
+ {
+ // Initialize
+ final Method initMethod = mgrClass.getMethod("init", (Class[]) null);
+ initMethod.invoke(mgr, (Object[]) null);
+ }
+ catch (final NoSuchMethodException ignored)
+ {
+ /* Ignore; don't initialize. */
+ }
+
+ return mgr;
+ }
+ catch (final InvocationTargetException e)
+ {
+ throw new FileSystemException("vfs/create-manager.error",
+ managerClassName,
+ e.getTargetException());
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("vfs/create-manager.error",
+ managerClassName,
+ e);
+ }
+ }
+
+ public static boolean isUriStyle()
+ {
+ if (uriStyle == null)
+ {
+ uriStyle = Boolean.FALSE;
+ }
+ return uriStyle.booleanValue();
+ }
+
+ public static void setUriStyle(final boolean uriStyle)
+ {
+ if (VFS.uriStyle != null && VFS.uriStyle.booleanValue() != uriStyle)
+ {
+ throw new IllegalStateException("VFS.uriStyle was already set differently.");
+ }
+ VFS.uriStyle = Boolean.valueOf(uriStyle);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/VfsLog.java b/trunk/core/src/main/java/org/apache/commons/vfs2/VfsLog.java
new file mode 100644
index 0000000..4149e58
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/VfsLog.java
@@ -0,0 +1,217 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+import org.apache.commons.logging.Log;
+
+/**
+ * This class is to keep the old logging behaviour (for ant-task) and to be able to
+ * correctly use commons-logging.<br>
+ * I hope i could remove it sometimes.
+ */
+public final class VfsLog
+{
+ // static utility class
+ private VfsLog()
+ {
+ }
+
+ /**
+ * warning.
+ * @param vfslog The base component Logger to use.
+ * @param commonslog The class specific Logger
+ * @param message The message to log.
+ * @param t The exception, if any.
+ */
+ public static void warn(final Log vfslog, final Log commonslog, final String message, final Throwable t)
+ {
+ if (vfslog != null)
+ {
+ vfslog.warn(message, t);
+ }
+ else if (commonslog != null)
+ {
+ commonslog.warn(message, t);
+ }
+ }
+
+ /**
+ * warning.
+ * @param vfslog The base component Logger to use.
+ * @param commonslog The class specific Logger
+ * @param message The message to log.
+ */
+ public static void warn(final Log vfslog, final Log commonslog, final String message)
+ {
+ if (vfslog != null)
+ {
+ vfslog.warn(message);
+ }
+ else if (commonslog != null)
+ {
+ commonslog.warn(message);
+ }
+ }
+
+ /**
+ * debug.
+ * @param vfslog The base component Logger to use.
+ * @param commonslog The class specific Logger
+ * @param message The message to log.
+ */
+ public static void debug(final Log vfslog, final Log commonslog, final String message)
+ {
+ if (vfslog != null)
+ {
+ vfslog.debug(message);
+ }
+ else if (commonslog != null)
+ {
+ commonslog.debug(message);
+ }
+ }
+
+ /**
+ * debug.
+ * @param vfslog The base component Logger to use.
+ * @param commonslog The class specific Logger
+ * @param message The message to log.
+ * @param t The exception, if any.
+ */
+ public static void debug(final Log vfslog, final Log commonslog, final String message, final Throwable t)
+ {
+ if (vfslog != null)
+ {
+ vfslog.debug(message, t);
+ }
+ else if (commonslog != null)
+ {
+ commonslog.debug(message, t);
+ }
+ }
+
+ /**
+ * info.
+ * @param vfslog The base component Logger to use.
+ * @param commonslog The class specific Logger
+ * @param message The message to log.
+ * @param t The exception, if any.
+ */
+ public static void info(final Log vfslog, final Log commonslog, final String message, final Throwable t)
+ {
+ if (vfslog != null)
+ {
+ vfslog.info(message, t);
+ }
+ else if (commonslog != null)
+ {
+ commonslog.info(message, t);
+ }
+ }
+
+ /**
+ * info.
+ * @param vfslog The base component Logger to use.
+ * @param commonslog The class specific Logger
+ * @param message The message to log.
+ */
+ public static void info(final Log vfslog, final Log commonslog, final String message)
+ {
+ if (vfslog != null)
+ {
+ vfslog.info(message);
+ }
+ else if (commonslog != null)
+ {
+ commonslog.info(message);
+ }
+ }
+
+ /**
+ * error.
+ * @param vfslog The base component Logger to use.
+ * @param commonslog The class specific Logger
+ * @param message The message to log.
+ * @param t The exception, if any.
+ */
+ public static void error(final Log vfslog, final Log commonslog, final String message, final Throwable t)
+ {
+ if (vfslog != null)
+ {
+ vfslog.error(message, t);
+ }
+ else if (commonslog != null)
+ {
+ commonslog.error(message, t);
+ }
+ }
+
+ /**
+ * error.
+ * @param vfslog The base component Logger to use.
+ * @param commonslog The class specific Logger
+ * @param message The message to log.
+ */
+ public static void error(final Log vfslog, final Log commonslog, final String message)
+ {
+ if (vfslog != null)
+ {
+ vfslog.error(message);
+ }
+ else if (commonslog != null)
+ {
+ commonslog.error(message);
+ }
+ }
+
+ /**
+ * fatal.
+ * @param vfslog The base component Logger to use.
+ * @param commonslog The class specific Logger
+ * @param message The message to log.
+ * @param t The exception, if any.
+ */
+ public static void fatal(final Log vfslog, final Log commonslog, final String message, final Throwable t)
+ {
+ if (vfslog != null)
+ {
+ vfslog.fatal(message, t);
+ }
+ else if (commonslog != null)
+ {
+ commonslog.fatal(message, t);
+ }
+ }
+
+ /**
+ * fatal.
+ * @param vfslog The base component Logger to use.
+ * @param commonslog The class specific Logger
+ * @param message The message to log.
+ */
+ public static void fatal(final Log vfslog, final Log commonslog, final String message)
+ {
+ if (vfslog != null)
+ {
+ vfslog.fatal(message);
+ }
+ else if (commonslog != null)
+ {
+ commonslog.fatal(message);
+ }
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/auth/StaticUserAuthenticator.java b/trunk/core/src/main/java/org/apache/commons/vfs2/auth/StaticUserAuthenticator.java
new file mode 100644
index 0000000..f142db9
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/auth/StaticUserAuthenticator.java
@@ -0,0 +1,205 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.auth;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.vfs2.UserAuthenticationData;
+import org.apache.commons.vfs2.UserAuthenticator;
+import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
+
+/**
+ * Provides always the same credentials data passed in with the constructor.
+ */
+public class StaticUserAuthenticator implements UserAuthenticator, Comparable<StaticUserAuthenticator>
+{
+ private static final Log LOG = LogFactory.getLog(StaticUserAuthenticator.class);
+
+ /** The user name */
+ private final String username;
+
+ /** The password */
+ private final String password;
+
+ /** The user's domain */
+ private final String domain;
+
+ public StaticUserAuthenticator(final String domain, final String username, final String password)
+ {
+ this.username = username;
+ this.password = password;
+ this.domain = domain;
+ }
+
+ @Override
+ public UserAuthenticationData requestAuthentication(final UserAuthenticationData.Type[] types)
+ {
+ final UserAuthenticationData data = new UserAuthenticationData();
+ for (final UserAuthenticationData.Type type : types)
+ {
+ if (type == UserAuthenticationData.DOMAIN)
+ {
+ data.setData(UserAuthenticationData.DOMAIN, UserAuthenticatorUtils.toChar(domain));
+ }
+ else if (type == UserAuthenticationData.USERNAME)
+ {
+ data.setData(UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(username));
+ }
+ else if (type == UserAuthenticationData.PASSWORD)
+ {
+ data.setData(UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(password));
+ }
+ else
+ {
+ if (LOG.isDebugEnabled())
+ {
+ LOG.debug(StaticUserAuthenticator.class.getSimpleName()
+ + " does not support authentication data type '" + type
+ + "'; authentication request for this type ignored.");
+ }
+ }
+ }
+ return data;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @since 2.0
+ */
+ @Override
+ public int hashCode()
+ {
+ final int prime = 37;
+ int result = 1;
+ result = prime * result + (domain == null ? 0 : domain.hashCode());
+ result = prime * result + (password == null ? 0 : password.hashCode());
+ result = prime * result + (username == null ? 0 : username.hashCode());
+
+ return result;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @since 2.0
+ */
+ @Override
+ public boolean equals(final Object obj)
+ {
+ if (this == obj)
+ {
+ return true;
+ }
+
+ if (obj == null)
+ {
+ return false;
+ }
+
+ if (getClass() != obj.getClass())
+ {
+ return false;
+ }
+
+ final StaticUserAuthenticator other = (StaticUserAuthenticator) obj;
+ return equalsNullsafe(domain, other.domain)
+ && equalsNullsafe(username, other.username)
+ && equalsNullsafe(password, other.password);
+ }
+
+ private boolean equalsNullsafe(final String thisString, final String otherString)
+ {
+ if (thisString == null)
+ {
+ if (otherString != null)
+ {
+ return false;
+ }
+ }
+ else if (!thisString.equals(otherString))
+ {
+ return false;
+ }
+ return true;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @since 2.0
+ */
+ @Override
+ public int compareTo(final StaticUserAuthenticator other)
+ {
+ int result = compareStringOrNull(domain, other.domain);
+ result = result == 0 ? compareStringOrNull(username, other.username) : result;
+ result = result == 0 ? compareStringOrNull(password, other.password) : result;
+
+ return result;
+ }
+
+ private int compareStringOrNull(final String thisString, final String otherString)
+ {
+ if (thisString == null)
+ {
+ if (otherString != null)
+ {
+ return -1;
+ }
+ }
+ else
+ {
+ if (otherString == null)
+ {
+ return 1;
+ }
+
+ final int result = thisString.compareTo(otherString);
+ if (result != 0)
+ {
+ return result;
+ }
+ }
+
+ return 0;
+ }
+
+ /**
+ * {@inheritDoc}
+ * @since 2.0
+ */
+ @Override
+ public String toString()
+ {
+ final StringBuilder buffer = new StringBuilder();
+ if (domain != null)
+ {
+ buffer.append(domain).append('\\');
+ }
+ if (username != null)
+ {
+ buffer.append(username);
+ }
+ else
+ {
+ buffer.append("(null)");
+ }
+ if (password != null)
+ {
+ buffer.append(":***");
+ }
+ return buffer.toString();
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/auth/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/auth/package.html
new file mode 100644
index 0000000..754cf02
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/auth/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>VFS Authentication implementation</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/cache/AbstractFilesCache.java b/trunk/core/src/main/java/org/apache/commons/vfs2/cache/AbstractFilesCache.java
new file mode 100644
index 0000000..b802777
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/cache/AbstractFilesCache.java
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.cache;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FilesCache;
+import org.apache.commons.vfs2.provider.AbstractVfsComponent;
+
+
+/**
+ * Abstract base class for FilesCache implementations.
+ */
+public abstract class AbstractFilesCache extends AbstractVfsComponent implements FilesCache
+{
+ // @Override - commented in FilesCache interface
+ public void touchFile(final FileObject file)
+ {
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/cache/DefaultFilesCache.java b/trunk/core/src/main/java/org/apache/commons/vfs2/cache/DefaultFilesCache.java
new file mode 100644
index 0000000..920d9d0
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/cache/DefaultFilesCache.java
@@ -0,0 +1,122 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.cache;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+
+/**
+ * A simple {@link org.apache.commons.vfs2.FilesCache FilesCache} implementation.
+ * <p>
+ * This implementation caches every file with no expire or limit.
+ * All files and filesystems are hard reachable references. This implementation
+ * holds a list of filesystem specific {@linkplain ConcurrentHashMap ConcurrentHashMaps} in
+ * the main cache map.
+ * <p>
+ * Cached {@linkplain FileObject FileObjects} as well as {@linkplain FileSystem FileSystems}
+ * are only removed when {@link #clear(FileSystem)} is called (i.e. on filesystem close).
+ * When the used {@link org.apache.commons.vfs2.FileSystemManager FileSystemManager} is closed,
+ * it will also {@linkplain #close() close} this cache (which frees all entries).
+ * <p>
+ * Despite its name, this is not the fallback implementation used by
+ * {@link org.apache.commons.vfs2.impl.DefaultFileSystemManager#init() DefaultFileSystemManager#init()}
+ * anymore.
+ */
+public class DefaultFilesCache extends AbstractFilesCache
+{
+ /** The FileSystem cache. Keeps one Map for each FileSystem. */
+ private final ConcurrentMap<FileSystem, ConcurrentMap<FileName, FileObject>> filesystemCache =
+ new ConcurrentHashMap<FileSystem, ConcurrentMap<FileName, FileObject>>(10);
+
+ @Override
+ public void putFile(final FileObject file)
+ {
+ final Map<FileName, FileObject> files = getOrCreateFilesystemCache(file.getFileSystem());
+ files.put(file.getName(), file);
+ }
+
+ @Override
+ public boolean putFileIfAbsent(final FileObject file)
+ {
+ final ConcurrentMap<FileName, FileObject> files = getOrCreateFilesystemCache(file.getFileSystem());
+ return files.putIfAbsent(file.getName(), file) == null;
+ }
+
+ @Override
+ public FileObject getFile(final FileSystem filesystem, final FileName name)
+ {
+ // avoid creating filesystem entry for empty filesystem cache:
+ final Map<FileName, FileObject> files = filesystemCache.get(filesystem);
+ if (files == null)
+ {
+ // cache for filesystem is not known => file is not cached:
+ return null;
+ }
+
+ return files.get(name); // or null
+ }
+
+ @Override
+ public void clear(final FileSystem filesystem)
+ {
+ // avoid keeping a reference to the FileSystem (key) object
+ final Map<FileName, FileObject> files = filesystemCache.remove(filesystem);
+ if (files != null)
+ {
+ files.clear(); // help GC
+ }
+ }
+
+ protected ConcurrentMap<FileName, FileObject> getOrCreateFilesystemCache(final FileSystem filesystem)
+ {
+ ConcurrentMap<FileName, FileObject> files = filesystemCache.get(filesystem);
+ // we loop to make sure we never return null even when concurrent clean is called
+ while (files == null)
+ {
+ filesystemCache.putIfAbsent(filesystem, new ConcurrentHashMap<FileName, FileObject>(200, 0.75f, 8));
+ files = filesystemCache.get(filesystem);
+ }
+
+ return files;
+ }
+
+ @Override
+ public void close()
+ {
+ super.close();
+
+ filesystemCache.clear();
+ }
+
+ @Override
+ public void removeFile(final FileSystem filesystem, final FileName name)
+ {
+ // avoid creating filesystem entry for empty filesystem cache:
+ final Map<FileName, FileObject> files = filesystemCache.get(filesystem);
+ if (files != null)
+ {
+ files.remove(name);
+ // This would be too racey:
+ // if (files.empty()) filesystemCache.remove(filessystem);
+ }
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/cache/FileSystemAndNameKey.java b/trunk/core/src/main/java/org/apache/commons/vfs2/cache/FileSystemAndNameKey.java
new file mode 100644
index 0000000..d9cdaa4
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/cache/FileSystemAndNameKey.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.cache;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystem;
+
+/**
+ * Key for various cache implementations.
+ * <p>
+ * It compares the fileSystem (by hashCode) and the filename.
+ */
+class FileSystemAndNameKey implements Comparable<FileSystemAndNameKey>
+{
+ /** The FileSystem */
+ private final FileSystem fileSystem;
+
+ /** The FileName */
+ private final FileName fileName;
+
+ /** hashcode to identify this object */
+ private final int fileSystemId;
+
+ FileSystemAndNameKey(final FileSystem fileSystem, final FileName fileName)
+ {
+ this.fileSystem = fileSystem;
+ this.fileSystemId = System.identityHashCode(fileSystem);
+
+ this.fileName = fileName;
+ }
+
+ @Override
+ public int compareTo(final FileSystemAndNameKey other)
+ {
+ if (fileSystemId < other.fileSystemId)
+ {
+ return -1;
+ }
+ if (fileSystemId > other.fileSystemId)
+ {
+ return 1;
+ }
+
+ return fileName.compareTo(other.fileName);
+ }
+
+ FileSystem getFileSystem()
+ {
+ return fileSystem;
+ }
+
+ FileName getFileName()
+ {
+ return fileName;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/cache/LRUFilesCache.java b/trunk/core/src/main/java/org/apache/commons/vfs2/cache/LRUFilesCache.java
new file mode 100644
index 0000000..eba5fcd
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/cache/LRUFilesCache.java
@@ -0,0 +1,263 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.cache;
+
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReadWriteLock;
+import java.util.concurrent.locks.ReentrantReadWriteLock;
+
+import org.apache.commons.collections4.map.AbstractLinkedMap;
+import org.apache.commons.collections4.map.LRUMap;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.VfsLog;
+import org.apache.commons.vfs2.util.Messages;
+
+/**
+ * This implementation caches every file using {@link LRUMap}.
+ * <p>
+ * The default constructor uses a LRU size of 100 per filesystem.
+ */
+public class LRUFilesCache extends AbstractFilesCache
+{
+ /** The default LRU size */
+ private static final int DEFAULT_LRU_SIZE = 100;
+
+ /** The logger to use. */
+ private static final Log log = LogFactory.getLog(LRUFilesCache.class);
+
+ /** The FileSystem cache */
+ private final ConcurrentMap<FileSystem, Map<FileName, FileObject>> filesystemCache =
+ new ConcurrentHashMap<FileSystem, Map<FileName, FileObject>>(10);
+
+ /** The size of the cache */
+ private final int lruSize;
+
+ private final ReadWriteLock rwLock = new ReentrantReadWriteLock();
+ private final Lock readLock = rwLock.readLock();
+ private final Lock writeLock = rwLock.writeLock();
+
+ /**
+ * The file cache
+ */
+ private class MyLRUMap extends LRUMap<FileName, FileObject>
+ {
+ /**
+ * serialVersionUID format is YYYYMMDD for the date of the last binary change.
+ */
+ private static final long serialVersionUID = 20101208L;
+
+ /** The FileSystem */
+ private final FileSystem filesystem;
+
+ public MyLRUMap(final FileSystem filesystem, final int size)
+ {
+ super(size, true);
+ this.filesystem = filesystem;
+ }
+
+ @Override
+ protected boolean removeLRU(final AbstractLinkedMap.LinkEntry<FileName, FileObject> linkEntry)
+ {
+ synchronized (LRUFilesCache.this)
+ {
+ final FileObject file = linkEntry.getValue();
+
+ // System.err.println(">>> " + size() + " check removeLRU:" + linkEntry.getKey().toString());
+
+ if (file.isAttached() || file.isContentOpen())
+ {
+ // do not allow open or attached files to be removed
+ // System.err.println(">>> " + size() + " VETO removeLRU:" +
+ // linkEntry.getKey().toString() + " (" + file.isAttached() + "/" +
+ // file.isContentOpen() + ")");
+ return false;
+ }
+
+ // System.err.println(">>> " + size() + " removeLRU:" + linkEntry.getKey().toString());
+ if (super.removeLRU(linkEntry))
+ {
+ try
+ {
+ // force detach
+ file.close();
+ }
+ catch (final FileSystemException e)
+ {
+ VfsLog.warn(getLogger(), log, Messages.getString("vfs.impl/LRUFilesCache-remove-ex.warn"), e);
+ }
+
+ final Map<?, ?> files = filesystemCache.get(filesystem);
+ if (files.size() < 1)
+ {
+ filesystemCache.remove(filesystem);
+ }
+
+ return true;
+ }
+
+ return false;
+ }
+ }
+ }
+
+ /**
+ * Default constructor. Uses a LRU size of 100 per filesystem.
+ */
+ public LRUFilesCache()
+ {
+ this(DEFAULT_LRU_SIZE);
+ }
+
+ /**
+ * Set the desired LRU size.
+ *
+ * @param lruSize the LRU size
+ */
+ public LRUFilesCache(final int lruSize)
+ {
+ this.lruSize = lruSize;
+ }
+
+ @Override
+ public void putFile(final FileObject file)
+ {
+ final Map<FileName, FileObject> files = getOrCreateFilesystemCache(file.getFileSystem());
+
+ writeLock.lock();
+ try
+ {
+ files.put(file.getName(), file);
+ }
+ finally
+ {
+ writeLock.unlock();
+ }
+ }
+
+
+ @Override
+ public boolean putFileIfAbsent(final FileObject file)
+ {
+ final Map<FileName, FileObject> files = getOrCreateFilesystemCache(file.getFileSystem());
+
+ writeLock.lock();
+ try
+ {
+ final FileName name = file.getName();
+
+ if (files.containsKey(name))
+ {
+ return false;
+ }
+
+ files.put(name, file);
+ return true;
+ }
+ finally
+ {
+ writeLock.unlock();
+ }
+ }
+
+ @Override
+ public FileObject getFile(final FileSystem filesystem, final FileName name)
+ {
+ final Map<FileName, FileObject> files = getOrCreateFilesystemCache(filesystem);
+
+ readLock.lock();
+ try
+ {
+ return files.get(name);
+ }
+ finally
+ {
+ readLock.unlock();
+ }
+ }
+
+ @Override
+ public void clear(final FileSystem filesystem)
+ {
+ final Map<FileName, FileObject> files = getOrCreateFilesystemCache(filesystem);
+
+ writeLock.lock();
+ try
+ {
+ files.clear();
+
+ filesystemCache.remove(filesystem);
+ }
+ finally
+ {
+ writeLock.unlock();
+ }
+ }
+
+ protected Map<FileName, FileObject> getOrCreateFilesystemCache(final FileSystem filesystem)
+ {
+ Map<FileName, FileObject> files = filesystemCache.get(filesystem);
+ if (files == null)
+ {
+ files = new MyLRUMap(filesystem, lruSize);
+ filesystemCache.putIfAbsent(filesystem, files);
+ }
+ return files;
+ }
+
+ @Override
+ public void close()
+ {
+ super.close();
+ filesystemCache.clear();
+ }
+
+ @Override
+ public void removeFile(final FileSystem filesystem, final FileName name)
+ {
+ final Map<?, ?> files = getOrCreateFilesystemCache(filesystem);
+
+ writeLock.lock();
+ try
+ {
+ files.remove(name);
+
+ if (files.size() < 1)
+ {
+ filesystemCache.remove(filesystem);
+ }
+ }
+ finally
+ {
+ writeLock.unlock();
+ }
+ }
+
+ @Override
+ public void touchFile(final FileObject file)
+ {
+ // this moves the file back on top
+ getFile(file.getFileSystem(), file.getName());
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/cache/NullFilesCache.java b/trunk/core/src/main/java/org/apache/commons/vfs2/cache/NullFilesCache.java
new file mode 100644
index 0000000..8f3146e
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/cache/NullFilesCache.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.cache;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+
+/**
+ * A {@link org.apache.commons.vfs2.FilesCache} implementation.
+ * <p>
+ * This implementation never ever caches a single file.
+ * <p>
+ * <b>Notice</b>: if you use resolveFile(uri) multiple times with the same path, the system will always
+ * create a new instance. Changes on one instance of this file are not seen by the others.
+ */
+public class NullFilesCache extends AbstractFilesCache
+{
+ @Override
+ public void putFile(final FileObject file)
+ {
+ }
+
+ @Override
+ public boolean putFileIfAbsent(final FileObject file)
+ {
+ return false;
+ }
+
+ @Override
+ public FileObject getFile(final FileSystem filesystem, final FileName name)
+ {
+ return null;
+ }
+
+ @Override
+ public void clear(final FileSystem filesystem)
+ {
+ }
+
+ @Override
+ public void removeFile(final FileSystem filesystem, final FileName name)
+ {
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/cache/OnCallRefreshFileObject.java b/trunk/core/src/main/java/org/apache/commons/vfs2/cache/OnCallRefreshFileObject.java
new file mode 100644
index 0000000..c7bed07
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/cache/OnCallRefreshFileObject.java
@@ -0,0 +1,200 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.cache;
+
+import java.util.List;
+
+import org.apache.commons.vfs2.FileContent;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSelector;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.NameScope;
+import org.apache.commons.vfs2.impl.DecoratedFileObject;
+
+/**
+ * This decorator refreshes the fileObject data on every call.
+ */
+public class OnCallRefreshFileObject extends DecoratedFileObject
+{
+ public OnCallRefreshFileObject(final FileObject fileObject)
+ {
+ super(fileObject);
+ }
+
+ @Override
+ public void close() throws FileSystemException
+ {
+ refresh();
+ super.close();
+ }
+
+ @Override
+ public void copyFrom(final FileObject srcFile, final FileSelector selector) throws FileSystemException
+ {
+ refresh();
+ super.copyFrom(srcFile, selector);
+ }
+
+ @Override
+ public void createFile() throws FileSystemException
+ {
+ refresh();
+ super.createFile();
+ }
+
+ @Override
+ public void createFolder() throws FileSystemException
+ {
+ refresh();
+ super.createFolder();
+ }
+
+ @Override
+ public boolean delete() throws FileSystemException
+ {
+ refresh();
+ return super.delete();
+ }
+
+ @Override
+ public int delete(final FileSelector selector) throws FileSystemException
+ {
+ refresh();
+ return super.delete(selector);
+ }
+
+ @Override
+ public boolean exists() throws FileSystemException
+ {
+ refresh();
+ return super.exists();
+ }
+
+ @Override
+ public void findFiles(final FileSelector selector, final boolean depthwise, final List<FileObject> selected)
+ throws FileSystemException
+ {
+ refresh();
+ super.findFiles(selector, depthwise, selected);
+ }
+
+ @Override
+ public FileObject[] findFiles(final FileSelector selector) throws FileSystemException
+ {
+ refresh();
+ return super.findFiles(selector);
+ }
+
+ @Override
+ public FileObject getChild(final String name) throws FileSystemException
+ {
+ refresh();
+ return super.getChild(name);
+ }
+
+ @Override
+ public FileObject[] getChildren() throws FileSystemException
+ {
+ refresh();
+ return super.getChildren();
+ }
+
+ @Override
+ public FileContent getContent() throws FileSystemException
+ {
+ refresh();
+ return super.getContent();
+ }
+
+ @Override
+ public FileType getType() throws FileSystemException
+ {
+ refresh();
+ return super.getType();
+ }
+
+ @Override
+ public boolean isExecutable() throws FileSystemException
+ {
+ refresh();
+ return super.isExecutable();
+ }
+
+ @Override
+ public boolean isHidden() throws FileSystemException
+ {
+ refresh();
+ return super.isHidden();
+ }
+
+ @Override
+ public boolean isReadable() throws FileSystemException
+ {
+ refresh();
+ return super.isReadable();
+ }
+
+ @Override
+ public boolean isWriteable() throws FileSystemException
+ {
+ refresh();
+ return super.isWriteable();
+ }
+
+ @Override
+ public boolean setExecutable(final boolean executable, final boolean ownerOnly) throws FileSystemException
+ {
+ refresh();
+ return super.setExecutable(executable, ownerOnly);
+ }
+
+ @Override
+ public boolean setReadable(final boolean readable, final boolean ownerOnly) throws FileSystemException
+ {
+ refresh();
+ return super.setReadable(readable, ownerOnly);
+ }
+
+ @Override
+ public boolean setWritable(final boolean writable, final boolean ownerOnly) throws FileSystemException
+ {
+ refresh();
+ return super.setWritable(writable, ownerOnly);
+ }
+
+ @Override
+ public void moveTo(final FileObject destFile) throws FileSystemException
+ {
+ refresh();
+ super.moveTo(destFile);
+ }
+
+ @Override
+ public FileObject resolveFile(final String name, final NameScope scope) throws FileSystemException
+ {
+ refresh();
+ return super.resolveFile(name, scope);
+ }
+
+ @Override
+ public FileObject resolveFile(final String path) throws FileSystemException
+ {
+ refresh();
+ return super.resolveFile(path);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/cache/SoftRefFilesCache.java b/trunk/core/src/main/java/org/apache/commons/vfs2/cache/SoftRefFilesCache.java
new file mode 100644
index 0000000..100abaf
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/cache/SoftRefFilesCache.java
@@ -0,0 +1,387 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.cache;
+
+import java.lang.ref.Reference;
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.SoftReference;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.atomic.AtomicReference;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.VfsLog;
+import org.apache.commons.vfs2.util.Messages;
+
+/**
+ * This implementation caches every file as long as it is strongly reachable by
+ * the java vm. As soon as the vm needs memory - every softly reachable file
+ * will be discarded.
+ *
+ * @see SoftReference
+ */
+public class SoftRefFilesCache extends AbstractFilesCache
+{
+ private static final int TIMEOUT = 1000;
+
+ private static final Log log = LogFactory.getLog(SoftRefFilesCache.class);
+
+ private final ConcurrentMap<FileSystem, Map<FileName, Reference<FileObject>>> fileSystemCache =
+ new ConcurrentHashMap<FileSystem, Map<FileName, Reference<FileObject>>>();
+ private final Map<Reference<FileObject>, FileSystemAndNameKey> refReverseMap =
+ new HashMap<Reference<FileObject>, FileSystemAndNameKey>(100);
+ private final ReferenceQueue<FileObject> refQueue = new ReferenceQueue<FileObject>();
+
+ private volatile SoftRefReleaseThread softRefReleaseThread = null; // @GuardedBy("lock")
+
+ private final Lock lock = new ReentrantLock();
+
+
+ /**
+ * This thread will listen on the ReferenceQueue and remove the entry in the
+ * filescache as soon as the vm removes the reference
+ */
+ private final class SoftRefReleaseThread extends Thread
+ {
+ private volatile boolean requestEnd; // used for inter-thread communication
+
+ private SoftRefReleaseThread()
+ {
+ setName(SoftRefReleaseThread.class.getName());
+ setDaemon(true);
+ }
+
+ @Override
+ public void run()
+ {
+ loop: while (!requestEnd && !Thread.currentThread().isInterrupted())
+ {
+ try
+ {
+ final Reference<?> ref = refQueue.remove(TIMEOUT);
+ if (ref == null)
+ {
+ continue;
+ }
+
+ lock.lock();
+ try
+ {
+ final FileSystemAndNameKey key = refReverseMap.get(ref);
+
+ if (key != null && removeFile(key))
+ {
+ close(key.getFileSystem());
+ }
+ }
+ finally
+ {
+ lock.unlock();
+ }
+ }
+ catch (final InterruptedException e)
+ {
+ if (!requestEnd)
+ {
+ VfsLog.warn(getLogger(), log,
+ Messages.getString("vfs.impl/SoftRefReleaseThread-interrupt.info"));
+ }
+ break loop;
+ }
+ }
+ }
+ }
+
+ public SoftRefFilesCache()
+ {
+ }
+
+ private void startThread()
+ {
+ // Double Checked Locking is allowed when volatile
+ if (softRefReleaseThread != null)
+ {
+ return;
+ }
+
+ synchronized (lock)
+ {
+ if (softRefReleaseThread == null)
+ {
+ softRefReleaseThread = new SoftRefReleaseThread();
+ softRefReleaseThread.start();
+ }
+ }
+ }
+
+ private void endThread()
+ {
+ synchronized (lock)
+ {
+ final SoftRefReleaseThread thread = softRefReleaseThread;
+ softRefReleaseThread = null;
+ if (thread != null)
+ {
+ thread.requestEnd = true;
+ thread.interrupt();
+ }
+ }
+ }
+
+ @Override
+ public void putFile(final FileObject fileObject)
+ {
+ if (log.isDebugEnabled())
+ {
+ log.debug("putFile: " + this.getSafeName(fileObject));
+ }
+
+ final Map<FileName, Reference<FileObject>> files = getOrCreateFilesystemCache(fileObject.getFileSystem());
+
+ final Reference<FileObject> ref = createReference(fileObject, refQueue);
+ final FileSystemAndNameKey key = new FileSystemAndNameKey(fileObject.getFileSystem(), fileObject.getName());
+
+ lock.lock();
+ try
+ {
+ final Reference<FileObject> old = files.put(fileObject.getName(), ref);
+ if (old != null)
+ {
+ refReverseMap.remove(old);
+ }
+ refReverseMap.put(ref, key);
+ }
+ finally
+ {
+ lock.unlock();
+ }
+ }
+
+ private String getSafeName(final FileName fileName)
+ {
+ return fileName.getFriendlyURI();
+ }
+
+ private String getSafeName(final FileObject fileObject)
+ {
+ return this.getSafeName(fileObject.getName());
+ }
+
+ @Override
+ public boolean putFileIfAbsent(final FileObject fileObject)
+ {
+ if (log.isDebugEnabled())
+ {
+ log.debug("putFile: " + this.getSafeName(fileObject));
+ }
+
+ final Map<FileName, Reference<FileObject>> files = getOrCreateFilesystemCache(fileObject.getFileSystem());
+
+ final Reference<FileObject> ref = createReference(fileObject, refQueue);
+ final FileSystemAndNameKey key = new FileSystemAndNameKey(fileObject.getFileSystem(), fileObject.getName());
+
+ lock.lock();
+ try
+ {
+ if (files.containsKey(fileObject.getName()) && files.get(fileObject.getName()).get() != null)
+ {
+ return false;
+ }
+ final Reference<FileObject> old = files.put(fileObject.getName(), ref);
+ if (old != null)
+ {
+ refReverseMap.remove(old);
+ }
+ refReverseMap.put(ref, key);
+ return true;
+ }
+ finally
+ {
+ lock.unlock();
+ }
+ }
+
+ protected Reference<FileObject> createReference(final FileObject file, final ReferenceQueue<FileObject> refqueue)
+ {
+ return new SoftReference<FileObject>(file, refqueue);
+ }
+
+ @Override
+ public FileObject getFile(final FileSystem fileSystem, final FileName fileName)
+ {
+ final Map<FileName, Reference<FileObject>> files = getOrCreateFilesystemCache(fileSystem);
+
+ lock.lock();
+ try
+ {
+ final Reference<FileObject> ref = files.get(fileName);
+ if (ref == null)
+ {
+ return null;
+ }
+
+ final FileObject fo = ref.get();
+ if (fo == null)
+ {
+ removeFile(fileSystem, fileName);
+ }
+ return fo;
+ }
+ finally
+ {
+ lock.unlock();
+ }
+ }
+
+ @Override
+ public void clear(final FileSystem fileSystem)
+ {
+ final Map<FileName, Reference<FileObject>> files = getOrCreateFilesystemCache(fileSystem);
+
+ lock.lock();
+ try
+ {
+ final Iterator<FileSystemAndNameKey> iterKeys = refReverseMap.values().iterator();
+ while (iterKeys.hasNext())
+ {
+ final FileSystemAndNameKey key = iterKeys.next();
+ if (key.getFileSystem() == fileSystem)
+ {
+ iterKeys.remove();
+ files.remove(key.getFileName());
+ }
+ }
+
+ if (files.size() < 1)
+ {
+ close(fileSystem);
+ }
+ }
+ finally
+ {
+ lock.unlock();
+ }
+ }
+
+ /**
+ * Called while the lock is held
+ * @param fileSystem The file system to close.
+ */
+ private void close(final FileSystem fileSystem)
+ {
+ if (log.isDebugEnabled())
+ {
+ log.debug("close fs: " + fileSystem.getRootName());
+ }
+
+ fileSystemCache.remove(fileSystem);
+ if (fileSystemCache.size() < 1)
+ {
+ endThread();
+ }
+ /* This is not thread-safe as another thread might be opening the file system
+ ((DefaultFileSystemManager) getContext().getFileSystemManager())
+ ._closeFileSystem(filesystem);
+ */
+ }
+
+ @Override
+ public void close()
+ {
+ super.close();
+
+ endThread();
+
+ lock.lock();
+ try
+ {
+ fileSystemCache.clear();
+
+ refReverseMap.clear();
+ }
+ finally
+ {
+ lock.unlock();
+ }
+ }
+
+ @Override
+ public void removeFile(final FileSystem fileSystem, final FileName fileName)
+ {
+ if (removeFile(new FileSystemAndNameKey(fileSystem, fileName)))
+ {
+ close(fileSystem);
+ }
+ }
+
+ private boolean removeFile(final FileSystemAndNameKey key)
+ {
+ if (log.isDebugEnabled())
+ {
+ log.debug("removeFile: " + this.getSafeName(key.getFileName()));
+ }
+
+ final Map<?, ?> files = getOrCreateFilesystemCache(key.getFileSystem());
+
+ lock.lock();
+ try
+ {
+ final Object ref = files.remove(key.getFileName());
+ if (ref != null)
+ {
+ refReverseMap.remove(ref);
+ }
+
+ return files.size() < 1;
+ }
+ finally
+ {
+ lock.unlock();
+ }
+ }
+
+ protected Map<FileName, Reference<FileObject>> getOrCreateFilesystemCache(final FileSystem fileSystem)
+ {
+ if (fileSystemCache.size() < 1)
+ {
+ startThread();
+ }
+
+ Map<FileName, Reference<FileObject>> files;
+
+ do
+ {
+ files = fileSystemCache.get(fileSystem);
+ if (files != null)
+ {
+ break;
+ }
+ files = new HashMap<FileName, Reference<FileObject>>();
+ } while (fileSystemCache.putIfAbsent(fileSystem, files) == null);
+
+ return files;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/cache/WeakRefFilesCache.java b/trunk/core/src/main/java/org/apache/commons/vfs2/cache/WeakRefFilesCache.java
new file mode 100644
index 0000000..a0d40f2
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/cache/WeakRefFilesCache.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.cache;
+
+import java.lang.ref.Reference;
+import java.lang.ref.ReferenceQueue;
+import java.lang.ref.WeakReference;
+
+import org.apache.commons.vfs2.FileObject;
+
+/**
+ * This implementation caches every file as long as it is strongly reachable by
+ * the java vm. As soon as the object is no longer reachable it will be discarded.
+ * In contrast to the SoftRefFilesCache this implementation might free resources faster
+ * as it don't wait until a memory limitation.
+ *
+ * @see java.lang.ref.WeakReference
+ */
+public class WeakRefFilesCache extends SoftRefFilesCache
+{
+ @Override
+ protected Reference<FileObject> createReference(final FileObject file, final ReferenceQueue<FileObject> refqueue)
+ {
+ return new WeakReference<FileObject>(file, refqueue);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/cache/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/cache/package.html
new file mode 100644
index 0000000..55f796a
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/cache/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>VFS File caching</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/events/AbstractFileChangeEvent.java b/trunk/core/src/main/java/org/apache/commons/vfs2/events/AbstractFileChangeEvent.java
new file mode 100644
index 0000000..ce4a9ae
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/events/AbstractFileChangeEvent.java
@@ -0,0 +1,34 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.events;
+
+import org.apache.commons.vfs2.FileChangeEvent;
+import org.apache.commons.vfs2.FileListener;
+import org.apache.commons.vfs2.FileObject;
+
+/**
+ * A change event that knows how to notify a listener.
+ */
+public abstract class AbstractFileChangeEvent extends FileChangeEvent
+{
+ public AbstractFileChangeEvent(final FileObject file)
+ {
+ super(file);
+ }
+
+ public abstract void notify(final FileListener listener) throws Exception;
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/events/ChangedEvent.java b/trunk/core/src/main/java/org/apache/commons/vfs2/events/ChangedEvent.java
new file mode 100644
index 0000000..5be75f0
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/events/ChangedEvent.java
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.events;
+
+import org.apache.commons.vfs2.FileListener;
+import org.apache.commons.vfs2.FileObject;
+
+/**
+ * File changed event.
+ */
+public class ChangedEvent extends AbstractFileChangeEvent
+{
+ public ChangedEvent(final FileObject file)
+ {
+ super(file);
+ }
+
+ @Override
+ public void notify(final FileListener listener) throws Exception
+ {
+ listener.fileChanged(this);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/events/CreateEvent.java b/trunk/core/src/main/java/org/apache/commons/vfs2/events/CreateEvent.java
new file mode 100644
index 0000000..26f35ec
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/events/CreateEvent.java
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.events;
+
+import org.apache.commons.vfs2.FileListener;
+import org.apache.commons.vfs2.FileObject;
+
+/**
+ * File creation event.
+ */
+public class CreateEvent extends AbstractFileChangeEvent
+{
+ public CreateEvent(final FileObject file)
+ {
+ super(file);
+ }
+
+ @Override
+ public void notify(final FileListener listener) throws Exception
+ {
+ listener.fileCreated(this);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/events/DeleteEvent.java b/trunk/core/src/main/java/org/apache/commons/vfs2/events/DeleteEvent.java
new file mode 100644
index 0000000..de4e775
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/events/DeleteEvent.java
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.events;
+
+import org.apache.commons.vfs2.FileListener;
+import org.apache.commons.vfs2.FileObject;
+
+/**
+ * File deletion event.
+ */
+public class DeleteEvent extends AbstractFileChangeEvent
+{
+ public DeleteEvent(final FileObject file)
+ {
+ super(file);
+ }
+
+ @Override
+ public void notify(final FileListener listener) throws Exception
+ {
+ listener.fileDeleted(this);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/events/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/events/package.html
new file mode 100644
index 0000000..acbdf79
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/events/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>VFS Events</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DecoratedFileObject.java b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DecoratedFileObject.java
new file mode 100644
index 0000000..07ef301
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DecoratedFileObject.java
@@ -0,0 +1,287 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.impl;
+
+import java.net.URL;
+import java.util.Iterator;
+import java.util.List;
+
+import org.apache.commons.vfs2.FileContent;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSelector;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.NameScope;
+import org.apache.commons.vfs2.operations.FileOperations;
+
+/**
+ * Base class to build a fileObject decoration.
+ */
+public class DecoratedFileObject implements FileObject
+{
+ private final FileObject decoratedFileObject;
+
+ public DecoratedFileObject(final FileObject decoratedFileObject)
+ {
+ super();
+ this.decoratedFileObject = decoratedFileObject;
+ }
+
+ @Override
+ public boolean canRenameTo(final FileObject newfile)
+ {
+ return decoratedFileObject.canRenameTo(newfile);
+ }
+
+ @Override
+ public void close() throws FileSystemException
+ {
+ decoratedFileObject.close();
+ }
+
+ @Override
+ public int compareTo(final FileObject fo)
+ {
+ return decoratedFileObject.compareTo(fo);
+ }
+
+ @Override
+ public void copyFrom(final FileObject srcFile, final FileSelector selector) throws FileSystemException
+ {
+ decoratedFileObject.copyFrom(srcFile, selector);
+ }
+
+ @Override
+ public void createFile() throws FileSystemException
+ {
+ decoratedFileObject.createFile();
+ }
+
+ @Override
+ public void createFolder() throws FileSystemException
+ {
+ decoratedFileObject.createFolder();
+ }
+
+ @Override
+ public boolean delete() throws FileSystemException
+ {
+ return decoratedFileObject.delete();
+ }
+
+ @Override
+ public int delete(final FileSelector selector) throws FileSystemException
+ {
+ return decoratedFileObject.delete(selector);
+ }
+
+ @Override
+ public int deleteAll() throws FileSystemException
+ {
+ return decoratedFileObject.deleteAll();
+ }
+
+ @Override
+ public boolean exists() throws FileSystemException
+ {
+ return decoratedFileObject.exists();
+ }
+
+ @Override
+ public FileObject[] findFiles(final FileSelector selector) throws FileSystemException
+ {
+ return decoratedFileObject.findFiles(selector);
+ }
+
+ @Override
+ public void findFiles(final FileSelector selector, final boolean depthwise, final List<FileObject> selected)
+ throws FileSystemException
+ {
+ decoratedFileObject.findFiles(selector, depthwise, selected);
+ }
+
+ @Override
+ public FileObject getChild(final String name) throws FileSystemException
+ {
+ return decoratedFileObject.getChild(name);
+ }
+
+ @Override
+ public FileObject[] getChildren() throws FileSystemException
+ {
+ return decoratedFileObject.getChildren();
+ }
+
+ @Override
+ public FileContent getContent() throws FileSystemException
+ {
+ return decoratedFileObject.getContent();
+ }
+
+ public FileObject getDecoratedFileObject()
+ {
+ return decoratedFileObject;
+ }
+
+ @Override
+ public FileOperations getFileOperations() throws FileSystemException
+ {
+ return decoratedFileObject.getFileOperations();
+ }
+
+ @Override
+ public FileSystem getFileSystem()
+ {
+ return decoratedFileObject.getFileSystem();
+ }
+
+ @Override
+ public String getPublicURIString()
+ {
+ return decoratedFileObject.getPublicURIString();
+ }
+
+ @Override
+ public FileName getName()
+ {
+ return decoratedFileObject.getName();
+ }
+
+ @Override
+ public FileObject getParent() throws FileSystemException
+ {
+ return decoratedFileObject.getParent();
+ }
+
+ @Override
+ public FileType getType() throws FileSystemException
+ {
+ return decoratedFileObject.getType();
+ }
+
+ @Override
+ public URL getURL() throws FileSystemException
+ {
+ return decoratedFileObject.getURL();
+ }
+
+ @Override
+ public boolean isAttached()
+ {
+ return decoratedFileObject.isAttached();
+ }
+
+ @Override
+ public boolean isContentOpen()
+ {
+ return decoratedFileObject.isContentOpen();
+ }
+
+ @Override
+ public boolean isExecutable() throws FileSystemException
+ {
+ return decoratedFileObject.isExecutable();
+ }
+
+ @Override
+ public boolean isFile() throws FileSystemException
+ {
+ return decoratedFileObject.isFile();
+ }
+
+ @Override
+ public boolean isFolder() throws FileSystemException
+ {
+ return decoratedFileObject.isFolder();
+ }
+
+ @Override
+ public boolean isHidden() throws FileSystemException
+ {
+ return decoratedFileObject.isHidden();
+ }
+
+ @Override
+ public boolean isReadable() throws FileSystemException
+ {
+ return decoratedFileObject.isReadable();
+ }
+
+ @Override
+ public boolean isWriteable() throws FileSystemException
+ {
+ return decoratedFileObject.isWriteable();
+ }
+
+ @Override
+ public Iterator<FileObject> iterator()
+ {
+ return decoratedFileObject.iterator();
+ }
+
+ @Override
+ public void moveTo(final FileObject destFile) throws FileSystemException
+ {
+ decoratedFileObject.moveTo(destFile);
+ }
+
+ @Override
+ public void refresh() throws FileSystemException
+ {
+ decoratedFileObject.refresh();
+ }
+
+ @Override
+ public FileObject resolveFile(final String path) throws FileSystemException
+ {
+ return decoratedFileObject.resolveFile(path);
+ }
+
+ @Override
+ public FileObject resolveFile(final String name, final NameScope scope) throws FileSystemException
+ {
+ return decoratedFileObject.resolveFile(name, scope);
+ }
+
+ @Override
+ public boolean setExecutable(final boolean executable, final boolean ownerOnly) throws FileSystemException
+ {
+ return decoratedFileObject.setExecutable(executable, ownerOnly);
+ }
+
+ @Override
+ public boolean setReadable(final boolean readable, final boolean ownerOnly) throws FileSystemException
+ {
+ return decoratedFileObject.setReadable(readable, ownerOnly);
+ }
+
+ @Override
+ public boolean setWritable(final boolean writable, final boolean ownerOnly) throws FileSystemException
+ {
+ return decoratedFileObject.setWritable(writable, ownerOnly);
+ }
+
+ @Override
+ public String toString()
+ {
+ return decoratedFileObject.toString();
+ }
+
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DefaultFileContentInfo.java b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DefaultFileContentInfo.java
new file mode 100644
index 0000000..7b5aded
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DefaultFileContentInfo.java
@@ -0,0 +1,46 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.impl;
+
+import org.apache.commons.vfs2.FileContentInfo;
+
+/**
+ * The default file content information.
+ */
+public class DefaultFileContentInfo implements FileContentInfo
+{
+ private final String contentType;
+ private final String contentEncoding;
+
+ public DefaultFileContentInfo(final String contentType, final String contentEncoding)
+ {
+ this.contentType = contentType;
+ this.contentEncoding = contentEncoding;
+ }
+
+ @Override
+ public String getContentType()
+ {
+ return contentType;
+ }
+
+ @Override
+ public String getContentEncoding()
+ {
+ return contentEncoding;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DefaultFileMonitor.java b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DefaultFileMonitor.java
new file mode 100644
index 0000000..ad4d22b
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DefaultFileMonitor.java
@@ -0,0 +1,677 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.impl;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Stack;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.vfs2.FileListener;
+import org.apache.commons.vfs2.FileMonitor;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.provider.AbstractFileSystem;
+
+/**
+ * A polling {@link FileMonitor} implementation.
+ * <p>
+ * The DefaultFileMonitor is a Thread based polling file system monitor with a 1
+ * second delay.
+ *
+ * <h2>Design:</h2>
+ *
+ * There is a Map of monitors known as FileMonitorAgents. With the thread running,
+ * each FileMonitorAgent object is asked to "check" on the file it is
+ * responsible for. To do this check, the cache is cleared.
+ * <ul>
+ * <li>If the file existed before the refresh and it no longer exists, a delete
+ * event is fired.</li>
+ * <li>If the file existed before the refresh and it still exists, check the
+ * last modified timestamp to see if that has changed.</li>
+ * <li>If it has, fire a change event.</li>
+ * </ul>
+ * With each file delete, the FileMonitorAgent of the parent is asked to
+ * re-build its
+ * list of children, so that they can be accurately checked when there are new
+ * children.
+ * <p>
+ * New files are detected during each "check" as each file does a check for new
+ * children.
+ * If new children are found, create events are fired recursively if recursive
+ * descent is enabled.
+ * <p>
+ * For performance reasons, added a delay that increases as the number of files
+ * monitored
+ * increases. The default is a delay of 1 second for every 1000 files processed.
+ *
+ * <h2>Example usage:</h2><pre>
+ * FileSystemManager fsManager = VFS.getManager();
+ * FileObject listendir = fsManager.resolveFile("/home/username/monitored/");
+ *
+ * DefaultFileMonitor fm = new DefaultFileMonitor(new CustomFileListener());
+ * fm.setRecursive(true);
+ * fm.addFile(listendir);
+ * fm.start();</pre>
+ * <i>(where CustomFileListener is a class that implements the FileListener
+ * interface.)</i>
+ */
+public class DefaultFileMonitor implements Runnable, FileMonitor
+{
+ private static final Log LOG = LogFactory.getLog(DefaultFileMonitor.class);
+
+ private static final long DEFAULT_DELAY = 1000;
+
+ private static final int DEFAULT_MAX_FILES = 1000;
+
+ /**
+ * Map from FileName to FileObject being monitored.
+ */
+ private final Map<FileName, FileMonitorAgent> monitorMap = new HashMap<FileName, FileMonitorAgent>();
+
+ /**
+ * The low priority thread used for checking the files being monitored.
+ */
+ private Thread monitorThread;
+
+ /**
+ * File objects to be removed from the monitor map.
+ */
+ private final Stack<FileObject> deleteStack = new Stack<FileObject>();
+
+ /**
+ * File objects to be added to the monitor map.
+ */
+ private final Stack<FileObject> addStack = new Stack<FileObject>();
+
+ /**
+ * A flag used to determine if the monitor thread should be running.
+ */
+ private volatile boolean shouldRun = true; // used for inter-thread communication
+
+ /**
+ * A flag used to determine if adding files to be monitored should be recursive.
+ */
+ private boolean recursive;
+
+ /**
+ * Set the delay between checks
+ */
+ private long delay = DEFAULT_DELAY;
+
+ /**
+ * Set the number of files to check until a delay will be inserted
+ */
+ private int checksPerRun = DEFAULT_MAX_FILES;
+
+ /**
+ * A listener object that if set, is notified on file creation and deletion.
+ */
+ private final FileListener listener;
+
+ public DefaultFileMonitor(final FileListener listener)
+ {
+ this.listener = listener;
+ }
+
+ /**
+ * Access method to get the recursive setting when adding files for monitoring.
+ * @return true if monitoring is enabled for children.
+ */
+ public boolean isRecursive()
+ {
+ return this.recursive;
+ }
+
+ /**
+ * Access method to set the recursive setting when adding files for monitoring.
+ * @param newRecursive true if monitoring should be enabled for children.
+ */
+ public void setRecursive(final boolean newRecursive)
+ {
+ this.recursive = newRecursive;
+ }
+
+ /**
+ * Access method to get the current FileListener object notified when there
+ * are changes with the files added.
+ * @return The FileListener.
+ */
+ FileListener getFileListener()
+ {
+ return this.listener;
+ }
+
+ /**
+ * Adds a file to be monitored.
+ * @param file The FileObject to monitor.
+ */
+ @Override
+ public void addFile(final FileObject file)
+ {
+ doAddFile(file);
+ try
+ {
+ // add all direct children too
+ if (file.getType().hasChildren())
+ {
+ // Traverse the children
+ final FileObject[] children = file.getChildren();
+ for (final FileObject element : children)
+ {
+ doAddFile(element);
+ }
+ }
+ }
+ catch (final FileSystemException fse)
+ {
+ LOG.error(fse.getLocalizedMessage(), fse);
+ }
+ }
+
+ /**
+ * Adds a file to be monitored.
+ * @param file The FileObject to add.
+ */
+ private void doAddFile(final FileObject file)
+ {
+ synchronized (this.monitorMap)
+ {
+ if (this.monitorMap.get(file.getName()) == null)
+ {
+ this.monitorMap.put(file.getName(), new FileMonitorAgent(this,
+ file));
+
+ try
+ {
+ if (this.listener != null)
+ {
+ file.getFileSystem().addListener(file, this.listener);
+ }
+
+ if (file.getType().hasChildren() && this.recursive)
+ {
+ // Traverse the children
+ final FileObject[] children = file.getChildren();
+ for (final FileObject element : children)
+ {
+ this.addFile(element); // Add depth first
+ }
+ }
+
+ }
+ catch (final FileSystemException fse)
+ {
+ LOG.error(fse.getLocalizedMessage(), fse);
+ }
+
+ }
+ }
+ }
+
+ /**
+ * Removes a file from being monitored.
+ * @param file The FileObject to remove from monitoring.
+ */
+ @Override
+ public void removeFile(final FileObject file)
+ {
+ synchronized (this.monitorMap)
+ {
+ final FileName fn = file.getName();
+ if (this.monitorMap.get(fn) != null)
+ {
+ FileObject parent;
+ try
+ {
+ parent = file.getParent();
+ }
+ catch (final FileSystemException fse)
+ {
+ parent = null;
+ }
+
+ this.monitorMap.remove(fn);
+
+ if (parent != null)
+ { // Not the root
+ final FileMonitorAgent parentAgent =
+ this.monitorMap.get(parent.getName());
+ if (parentAgent != null)
+ {
+ parentAgent.resetChildrenList();
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Queues a file for removal from being monitored.
+ * @param file The FileObject to be removed from being monitored.
+ */
+ protected void queueRemoveFile(final FileObject file)
+ {
+ this.deleteStack.push(file);
+ }
+
+ /**
+ * Get the delay between runs.
+ * @return The delay period.
+ */
+ public long getDelay()
+ {
+ return delay;
+ }
+
+ /**
+ * Set the delay between runs.
+ * @param delay The delay period.
+ */
+ public void setDelay(final long delay)
+ {
+ if (delay > 0)
+ {
+ this.delay = delay;
+ }
+ else
+ {
+ this.delay = DEFAULT_DELAY;
+ }
+ }
+
+ /**
+ * get the number of files to check per run.
+ * @return The number of files to check per iteration.
+ */
+ public int getChecksPerRun()
+ {
+ return checksPerRun;
+ }
+
+ /**
+ * set the number of files to check per run.
+ * a additional delay will be added if there are more files to check
+ *
+ * @param checksPerRun a value less than 1 will disable this feature
+ */
+ public void setChecksPerRun(final int checksPerRun)
+ {
+ this.checksPerRun = checksPerRun;
+ }
+
+ /**
+ * Queues a file for addition to be monitored.
+ * @param file The FileObject to add.
+ */
+ protected void queueAddFile(final FileObject file)
+ {
+ this.addStack.push(file);
+ }
+
+ /**
+ * Starts monitoring the files that have been added.
+ */
+ public void start()
+ {
+ if (this.monitorThread == null)
+ {
+ this.monitorThread = new Thread(this);
+ this.monitorThread.setDaemon(true);
+ this.monitorThread.setPriority(Thread.MIN_PRIORITY);
+ }
+ this.monitorThread.start();
+ }
+
+ /**
+ * Stops monitoring the files that have been added.
+ */
+ public void stop()
+ {
+ this.shouldRun = false;
+ }
+
+ /**
+ * Asks the agent for each file being monitored to check its file for changes.
+ */
+ @Override
+ public void run()
+ {
+ mainloop:
+ while (!monitorThread.isInterrupted() && this.shouldRun)
+ {
+ // For each entry in the map
+ Object[] fileNames;
+ synchronized (this.monitorMap)
+ {
+ fileNames = this.monitorMap.keySet().toArray();
+ }
+ for (int iterFileNames = 0; iterFileNames < fileNames.length;
+ iterFileNames++)
+ {
+ final FileName fileName = (FileName) fileNames[iterFileNames];
+ FileMonitorAgent agent;
+ synchronized (this.monitorMap)
+ {
+ agent = this.monitorMap.get(fileName);
+ }
+ if (agent != null)
+ {
+ agent.check();
+ }
+
+ if (getChecksPerRun() > 0 && (iterFileNames + 1) % getChecksPerRun() == 0)
+ {
+ try
+ {
+ Thread.sleep(getDelay());
+ }
+ catch (final InterruptedException e)
+ {
+ // Woke up.
+ }
+ }
+
+ if (monitorThread.isInterrupted() || !this.shouldRun)
+ {
+ continue mainloop;
+ }
+ }
+
+ while (!this.addStack.empty())
+ {
+ this.addFile(this.addStack.pop());
+ }
+
+ while (!this.deleteStack.empty())
+ {
+ this.removeFile(this.deleteStack.pop());
+ }
+
+ try
+ {
+ Thread.sleep(getDelay());
+ }
+ catch (final InterruptedException e)
+ {
+ continue;
+ }
+ }
+
+ this.shouldRun = true;
+ }
+
+ /**
+ * File monitor agent.
+ */
+ private static final class FileMonitorAgent
+ {
+ private final FileObject file;
+ private final DefaultFileMonitor fm;
+
+ private boolean exists;
+ private long timestamp;
+ private Map<FileName, Object> children;
+
+ private FileMonitorAgent(final DefaultFileMonitor fm, final FileObject file)
+ {
+ this.fm = fm;
+ this.file = file;
+
+ this.refresh();
+ this.resetChildrenList();
+
+ try
+ {
+ this.exists = this.file.exists();
+ }
+ catch (final FileSystemException fse)
+ {
+ this.exists = false;
+ this.timestamp = -1;
+ }
+
+ if (this.exists)
+ {
+ try
+ {
+ this.timestamp = this.file.getContent().getLastModifiedTime();
+ }
+ catch (final FileSystemException fse)
+ {
+ this.timestamp = -1;
+ }
+ }
+ }
+
+ private void resetChildrenList()
+ {
+ try
+ {
+ if (this.file.getType().hasChildren())
+ {
+ this.children = new HashMap<FileName, Object>();
+ final FileObject[] childrenList = this.file.getChildren();
+ for (final FileObject element : childrenList)
+ {
+ this.children.put(element.getName(), new
+ Object()); // null?
+ }
+ }
+ }
+ catch (final FileSystemException fse)
+ {
+ this.children = null;
+ }
+ }
+
+
+ /**
+ * Clear the cache and re-request the file object
+ */
+ private void refresh()
+ {
+ try
+ {
+ this.file.refresh();
+ }
+ catch (final FileSystemException fse)
+ {
+ LOG.error(fse.getLocalizedMessage(), fse);
+ }
+ }
+
+
+ /**
+ * Recursively fires create events for all children if recursive descent is
+ * enabled. Otherwise the create event is only fired for the initial
+ * FileObject.
+ * @param child The child to add.
+ */
+ private void fireAllCreate(final FileObject child)
+ {
+ // Add listener so that it can be triggered
+ if (this.fm.getFileListener() != null)
+ {
+ child.getFileSystem().addListener(child, this.fm.getFileListener());
+ }
+
+ ((AbstractFileSystem) child.getFileSystem()).fireFileCreated(child);
+
+ // Remove it because a listener is added in the queueAddFile
+ if (this.fm.getFileListener() != null)
+ {
+ child.getFileSystem().removeListener(child,
+ this.fm.getFileListener());
+ }
+
+ this.fm.queueAddFile(child); // Add
+
+ try
+ {
+ if (this.fm.isRecursive() && child.getType().hasChildren())
+ {
+ final FileObject[] newChildren = child.getChildren();
+ for (final FileObject element : newChildren)
+ {
+ fireAllCreate(element);
+ }
+ }
+ }
+ catch (final FileSystemException fse)
+ {
+ LOG.error(fse.getLocalizedMessage(), fse);
+ }
+ }
+
+ /**
+ * Only checks for new children. If children are removed, they'll
+ * eventually be checked.
+ */
+ private void checkForNewChildren()
+ {
+ try
+ {
+ if (this.file.getType().hasChildren())
+ {
+ final FileObject[] newChildren = this.file.getChildren();
+ if (this.children != null)
+ {
+ // See which new children are not listed in the current children map.
+ final Map<FileName, Object> newChildrenMap = new HashMap<FileName, Object>();
+ final Stack<FileObject> missingChildren = new Stack<FileObject>();
+
+ for (int i = 0; i < newChildren.length; i++)
+ {
+ newChildrenMap.put(newChildren[i].getName(), new
+ Object()); // null ?
+ // If the child's not there
+ if
+ (!this.children.containsKey(newChildren[i].getName()))
+ {
+ missingChildren.push(newChildren[i]);
+ }
+ }
+
+ this.children = newChildrenMap;
+
+ // If there were missing children
+ if (!missingChildren.empty())
+ {
+
+ while (!missingChildren.empty())
+ {
+ final FileObject child = missingChildren.pop();
+ this.fireAllCreate(child);
+ }
+ }
+
+ }
+ else
+ {
+ // First set of children - Break out the cigars
+ if (newChildren.length > 0)
+ {
+ this.children = new HashMap<FileName, Object>();
+ }
+ for (final FileObject element : newChildren)
+ {
+ this.children.put(element.getName(), new
+ Object()); // null?
+ this.fireAllCreate(element);
+ }
+ }
+ }
+ }
+ catch (final FileSystemException fse)
+ {
+ LOG.error(fse.getLocalizedMessage(), fse);
+ }
+ }
+
+ private void check()
+ {
+ this.refresh();
+
+ try
+ {
+ // If the file existed and now doesn't
+ if (this.exists && !this.file.exists())
+ {
+ this.exists = this.file.exists();
+ this.timestamp = -1;
+
+ // Fire delete event
+
+ ((AbstractFileSystem)
+ this.file.getFileSystem()).fireFileDeleted(this.file);
+
+ // Remove listener in case file is re-created. Don't want to fire twice.
+ if (this.fm.getFileListener() != null)
+ {
+ this.file.getFileSystem().removeListener(this.file,
+ this.fm.getFileListener());
+ }
+
+ // Remove from map
+ this.fm.queueRemoveFile(this.file);
+ }
+ else if (this.exists && this.file.exists())
+ {
+
+ // Check the timestamp to see if it has been modified
+ if (this.timestamp != this.file.getContent().getLastModifiedTime())
+ {
+ this.timestamp = this.file.getContent().getLastModifiedTime();
+ // Fire change event
+
+ // Don't fire if it's a folder because new file children
+ // and deleted files in a folder have their own event triggered.
+ if (!this.file.getType().hasChildren())
+ {
+ ((AbstractFileSystem)
+ this.file.getFileSystem()).fireFileChanged(this.file);
+ }
+ }
+
+ }
+ else if (!this.exists && this.file.exists())
+ {
+ this.exists = this.file.exists();
+ this.timestamp = this.file.getContent().getLastModifiedTime();
+ // Don't fire if it's a folder because new file children
+ // and deleted files in a folder have their own event triggered.
+ if (!this.file.getType().hasChildren())
+ {
+ ((AbstractFileSystem)
+ this.file.getFileSystem()).fireFileCreated(this.file);
+ }
+ }
+
+ this.checkForNewChildren();
+
+ }
+ catch (final FileSystemException fse)
+ {
+ LOG.error(fse.getLocalizedMessage(), fse);
+ }
+ }
+
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DefaultFileReplicator.java b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DefaultFileReplicator.java
new file mode 100644
index 0000000..819981b
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DefaultFileReplicator.java
@@ -0,0 +1,263 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.impl;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.Random;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSelector;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.VfsLog;
+import org.apache.commons.vfs2.provider.AbstractVfsComponent;
+import org.apache.commons.vfs2.provider.FileReplicator;
+import org.apache.commons.vfs2.provider.TemporaryFileStore;
+import org.apache.commons.vfs2.provider.UriParser;
+import org.apache.commons.vfs2.util.Messages;
+
+/**
+ * A simple file replicator and temporary file store.
+ */
+public class DefaultFileReplicator
+ extends AbstractVfsComponent
+ implements FileReplicator, TemporaryFileStore
+{
+ private static final Log log = LogFactory.getLog(DefaultFileReplicator.class);
+ private static final int MASK = 0xffff;
+
+ private static final Random random = new Random();
+
+ private static final char[] TMP_RESERVED_CHARS = new char[]
+ {
+ '?', '/', '\\', ' ', '&', '"', '\'', '*', '#', ';', ':', '<', '>', '|'
+ };
+
+ private final ArrayList<Object> copies = new ArrayList<Object>();
+ private long filecount;
+ private File tempDir;
+ private boolean tempDirMessageLogged;
+
+ public DefaultFileReplicator()
+ {
+ }
+
+ /**
+ * Constructor to set the location of the temporary directory.
+ *
+ * @param tempDir The temporary directory.
+ */
+ public DefaultFileReplicator(final File tempDir)
+ {
+ this.tempDir = tempDir;
+ }
+
+ protected void addFile(final Object file)
+ {
+ synchronized (copies)
+ {
+ copies.add(file);
+ }
+ }
+
+ /**
+ * Allocates a new temporary file.
+ *
+ * @param baseName the base file name.
+ * @return The created File.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public File allocateFile(final String baseName) throws FileSystemException
+ {
+ // Create a unique-ish file name
+ final String basename = createFilename(baseName);
+ synchronized (this)
+ {
+ filecount++;
+ }
+
+ return createAndAddFile(tempDir, basename);
+ }
+
+ /**
+ * Closes the replicator, deleting all temporary files.
+ */
+ @Override
+ public void close()
+ {
+ // Delete the temporary files
+ synchronized (copies)
+ {
+ while (copies.size() > 0)
+ {
+ final File file = (File) removeFile();
+ deleteFile(file);
+ }
+ }
+
+ // Clean up the temp directory, if it is empty
+ if (tempDir != null && tempDir.exists() && tempDir.list().length == 0)
+ {
+ tempDir.delete();
+ tempDir = null;
+ }
+ }
+
+ protected File createAndAddFile(final File parent, final String basename) throws FileSystemException
+ {
+ final File file = createFile(tempDir, basename);
+
+ // Keep track to delete later
+ addFile(file);
+
+ return file;
+ }
+
+ /**
+ * Create the temporary file.
+ *
+ * @param parent The file to use as the parent of the file being created.
+ * @param name The name of the file to create.
+ * @return The File that was created.
+ * @throws FileSystemException if an error occurs creating the file.
+ */
+ protected File createFile(final File parent, final String name) throws FileSystemException
+ {
+ return new File(parent, UriParser.decode(name));
+ }
+
+ /**
+ * Create the temporary file name.
+ *
+ * @param baseName The base to prepend to the file name being created.
+ * @return the name of the File.
+ */
+ protected String createFilename(final String baseName)
+ {
+ // BUG29007
+ // return baseName + "_" + getFilecount() + ".tmp";
+
+ // imario@apache.org: BUG34976 get rid of maybe reserved and dangerous characters
+ // e.g. to allow replication of http://hostname.org/fileservlet?file=abc.txt
+ final String safeBasename = UriParser.encode(baseName, TMP_RESERVED_CHARS).replace('%', '_');
+ return "tmp_" + getFilecount() + "_" + safeBasename;
+ }
+
+ /**
+ * Physically deletes the file from the filesystem.
+ *
+ * @param file The File to delete.
+ */
+ protected void deleteFile(final File file)
+ {
+ try
+ {
+ final FileObject fileObject = getContext().toFileObject(file);
+ fileObject.deleteAll();
+ }
+ catch (final FileSystemException e)
+ {
+ final String message = Messages.getString("vfs.impl/delete-temp.warn", file.getName());
+ VfsLog.warn(getLogger(), log, message, e);
+ }
+ }
+
+ protected long getFilecount()
+ {
+ return filecount;
+ }
+
+ /**
+ * Initializes this component.
+ *
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public void init() throws FileSystemException
+ {
+ if (tempDir == null)
+ {
+ final String baseTmpDir = System.getProperty("java.io.tmpdir");
+
+ tempDir = new File(baseTmpDir, "vfs_cache").getAbsoluteFile();
+ }
+
+ filecount = random.nextInt() & MASK;
+
+ if (!tempDirMessageLogged)
+ {
+ final String message = Messages.getString("vfs.impl/temp-dir.info", tempDir);
+ VfsLog.info(getLogger(), log, message);
+
+ tempDirMessageLogged = true;
+ }
+ }
+
+ /**
+ * Removes a file from the copies list. Will be used for cleanup.
+ * <p>
+ * Notice: The system awaits that the returning object can be cast to a {@link java.io.File}.
+ *
+ * @return the File that was removed.
+ */
+ protected Object removeFile()
+ {
+ synchronized (copies)
+ {
+ return copies.remove(0);
+ }
+ }
+
+ /**
+ * Removes a instance from the list of copies.
+ *
+ * @param file The File to remove.
+ */
+ protected void removeFile(final Object file)
+ {
+ synchronized (copies)
+ {
+ copies.remove(file);
+ }
+ }
+
+ /**
+ * Creates a local copy of the file, and all its descendants.
+ *
+ * @param srcFile The file to copy.
+ * @param selector The FileSelector.
+ * @return the created File.
+ * @throws FileSystemException if an error occurs copying the file.
+ */
+ @Override
+ public File replicateFile(final FileObject srcFile,
+ final FileSelector selector)
+ throws FileSystemException
+ {
+ final String basename = srcFile.getName().getBaseName();
+ final File file = allocateFile(basename);
+
+ // Copy from the source file
+ final FileObject destFile = getContext().toFileObject(file);
+ destFile.copyFrom(srcFile, selector);
+
+ return file;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DefaultFileSystemConfigBuilder.java b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DefaultFileSystemConfigBuilder.java
new file mode 100644
index 0000000..0ee7950
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DefaultFileSystemConfigBuilder.java
@@ -0,0 +1,77 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.impl;
+
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemConfigBuilder;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.UserAuthenticator;
+
+/**
+ * Default options usable for all file systems.
+ */
+public class DefaultFileSystemConfigBuilder extends FileSystemConfigBuilder
+{
+ /** The default FileSystemConfigBuilder */
+ private static final DefaultFileSystemConfigBuilder BUILDER = new DefaultFileSystemConfigBuilder();
+
+ /**
+ * Gets the singleton builder.
+ *
+ * @return the singleton builder.
+ */
+ public static DefaultFileSystemConfigBuilder getInstance()
+ {
+ return BUILDER;
+ }
+
+ /**
+ * Sets the user authenticator to get authentication informations.
+ * @param opts The FileSystemOptions.
+ * @param userAuthenticator The UserAuthenticator.
+ * @throws FileSystemException if an error occurs setting the UserAuthenticator.
+ */
+ public void setUserAuthenticator(final FileSystemOptions opts, final UserAuthenticator userAuthenticator)
+ throws FileSystemException
+ {
+ setParam(opts, "userAuthenticator", userAuthenticator);
+ }
+
+ /**
+ * @see #setUserAuthenticator
+ * @param opts The FileSystemOptions.
+ * @return The UserAuthenticator.
+ */
+ public UserAuthenticator getUserAuthenticator(final FileSystemOptions opts)
+ {
+ return (UserAuthenticator) getParam(opts, "userAuthenticator");
+ }
+
+ /**
+ * Dummy class that implements FileSystem.
+ */
+ abstract static class DefaultFileSystem implements FileSystem
+ {
+ }
+
+ @Override
+ protected Class<? extends FileSystem> getConfigClass()
+ {
+ return DefaultFileSystem.class;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DefaultFileSystemManager.java b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DefaultFileSystemManager.java
new file mode 100644
index 0000000..220a4ec
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DefaultFileSystemManager.java
@@ -0,0 +1,1341 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.impl;
+
+import java.io.File;
+import java.lang.reflect.Constructor;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.net.URL;
+import java.net.URLStreamHandler;
+import java.net.URLStreamHandlerFactory;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.vfs2.CacheStrategy;
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileContentInfoFactory;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemConfigBuilder;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.FilesCache;
+import org.apache.commons.vfs2.NameScope;
+import org.apache.commons.vfs2.VFS;
+import org.apache.commons.vfs2.cache.SoftRefFilesCache;
+import org.apache.commons.vfs2.operations.FileOperationProvider;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileProvider;
+import org.apache.commons.vfs2.provider.DefaultURLStreamHandler;
+import org.apache.commons.vfs2.provider.FileProvider;
+import org.apache.commons.vfs2.provider.FileReplicator;
+import org.apache.commons.vfs2.provider.LocalFileProvider;
+import org.apache.commons.vfs2.provider.TemporaryFileStore;
+import org.apache.commons.vfs2.provider.UriParser;
+import org.apache.commons.vfs2.provider.VfsComponent;
+
+/**
+ * The default file system manager implementation.
+ */
+public class DefaultFileSystemManager implements FileSystemManager
+{
+ /**
+ * Mapping from URI scheme to FileProvider.
+ */
+ private final Map<String, FileProvider> providers = new HashMap<String, FileProvider>();
+
+ /**
+ * All components used by this manager.
+ */
+ private final ArrayList<Object> components = new ArrayList<Object>();
+
+ /**
+ * The context to pass to providers.
+ */
+ private final DefaultVfsComponentContext context = new DefaultVfsComponentContext(this);
+
+ /**
+ * Operations providers added to this manager.
+ */
+ private final Map<String, List<FileOperationProvider>> operationProviders =
+ new HashMap<String, List<FileOperationProvider>>();
+
+ /**
+ * Mappings of file types.
+ */
+ private final FileTypeMap typeMap = new FileTypeMap();
+
+
+ /**
+ * The provider for local files.
+ */
+ private LocalFileProvider localFileProvider;
+
+ /**
+ * The default provider.
+ */
+ private FileProvider defaultProvider;
+
+ /**
+ * The file replicator to use.
+ */
+ private FileReplicator fileReplicator;
+
+ /**
+ * The base file to use for relative URI.
+ */
+ private FileObject baseFile;
+
+ /**
+ * The files cache
+ */
+ private FilesCache filesCache;
+
+ /**
+ * The cache strategy
+ */
+ private CacheStrategy fileCacheStrategy;
+
+ /**
+ * Class which decorates all returned fileObjects
+ */
+ private Class<?> fileObjectDecorator;
+ /**
+ * Reflection constructor extracted from {@link #fileObjectDecorator}
+ */
+ private Constructor<?> fileObjectDecoratorConst;
+
+ /**
+ * The class to use to determine the content-type (mime-type)
+ */
+ private FileContentInfoFactory fileContentInfoFactory;
+
+ /**
+ * The logger to use. Default implementation.
+ */
+ private Log log = LogFactory.getLog(getClass());
+
+ /**
+ * The temporary file store to use.
+ */
+ private TemporaryFileStore tempFileStore;
+
+ /**
+ * The virtual file provider.
+ */
+ private VirtualFileProvider vfsProvider;
+
+ /**
+ * Flag, if manager is initialized (after init() and before close()).
+ */
+ private boolean init;
+
+
+ /**
+ * Returns the logger used by this manager.
+ * @return the Logger.
+ */
+ protected Log getLogger()
+ {
+ return log;
+ }
+
+ /**
+ * Registers a file system provider.
+ * <p>
+ * The manager takes care of all lifecycle management.
+ * A provider may be registered multiple times.
+ * The first {@link LocalFileProvider} added will be
+ * remembered for {@link #getLocalFileProvider()}.
+ *
+ * @param urlScheme
+ * The scheme the provider will handle.
+ * @param provider
+ * The provider.
+ * @throws FileSystemException if an error occurs adding the provider.
+ */
+ public void addProvider(final String urlScheme, final FileProvider provider)
+ throws FileSystemException
+ {
+ addProvider(new String[] {urlScheme}, provider);
+ }
+
+ /**
+ * Registers a file system provider.
+ * <p>
+ * The manager takes care of all lifecycle management.
+ * A provider may be registered multiple times.
+ * The first {@link LocalFileProvider} added will be
+ * remembered for {@link #getLocalFileProvider()}.
+ *
+ * @param urlSchemes
+ * The schemes the provider will handle.
+ * @param provider
+ * The provider.
+ * @throws FileSystemException if an error occurs adding the provider.
+ */
+ public void addProvider(final String[] urlSchemes,
+ final FileProvider provider) throws FileSystemException
+ {
+ // fail duplicate schemes
+ for (final String scheme : urlSchemes)
+ {
+ if (providers.containsKey(scheme))
+ {
+ throw new FileSystemException(
+ "vfs.impl/multiple-providers-for-scheme.error", scheme);
+ }
+ }
+
+ // Contextualise the component (if not already)
+ setupComponent(provider);
+
+ // Add to map
+ for (final String scheme : urlSchemes)
+ {
+ providers.put(scheme, provider);
+ }
+
+ if (provider instanceof LocalFileProvider && localFileProvider == null)
+ {
+ localFileProvider = (LocalFileProvider) provider;
+ }
+ }
+
+ /**
+ * Returns true if this manager has a provider for a particular scheme.
+ *
+ * @param scheme The scheme to check.
+ * @return true if a provider is configured for this scheme, false otherwise.
+ */
+ @Override
+ public boolean hasProvider(final String scheme)
+ {
+ return providers.containsKey(scheme);
+ }
+
+ /**
+ * Adds an filename extension mapping.
+ *
+ * @param extension The file name extension.
+ * @param scheme The scheme to use for files with this extension.
+ */
+ public void addExtensionMap(final String extension, final String scheme)
+ {
+ typeMap.addExtension(extension, scheme);
+ }
+
+ /**
+ * Adds a mime type mapping.
+ *
+ * @param mimeType The mime type.
+ * @param scheme The scheme to use for files with this mime type.
+ */
+ public void addMimeTypeMap(final String mimeType, final String scheme)
+ {
+ typeMap.addMimeType(mimeType, scheme);
+ }
+
+ /**
+ * Sets the default provider. This is the provider that will handle URI with
+ * unknown schemes. The manager takes care of all lifecycle management.
+ * @param provider The FileProvider.
+ * @throws FileSystemException if an error occurs setting the provider.
+ */
+ public void setDefaultProvider(final FileProvider provider)
+ throws FileSystemException
+ {
+ setupComponent(provider);
+ defaultProvider = provider;
+ }
+
+ /**
+ * Returns the filesCache implementation used to cache files.
+ * @return The FilesCache.
+ */
+ @Override
+ public FilesCache getFilesCache()
+ {
+ return filesCache;
+ }
+
+ /**
+ * Sets the filesCache implementation used to cache files.
+ * <p>
+ * Can only be set before the FileSystemManager is initialized.
+ * <p>
+ * The manager takes care of the lifecycle. If none is set, a default is picked
+ * in {@link #init()}.
+ *
+ * @param filesCache The FilesCache.
+ * @throws FileSystemException if an error occurs setting the cache..
+ */
+ public void setFilesCache(final FilesCache filesCache)
+ throws FileSystemException
+ {
+ if (init)
+ {
+ throw new FileSystemException("vfs.impl/already-inited.error");
+ }
+
+ this.filesCache = filesCache;
+ }
+
+ /**
+ * Set the cache strategy to use when dealing with file object data.
+ * <p>
+ * Can only be set before the FileSystemManager is initialized.
+ * <p>
+ * The default is {@link CacheStrategy#ON_RESOLVE}
+ *
+ * @param fileCacheStrategy The CacheStrategy to use.
+ * @throws FileSystemException
+ * if this is not possible. e.g. it is already set.
+ */
+ public void setCacheStrategy(final CacheStrategy fileCacheStrategy)
+ throws FileSystemException
+ {
+ if (init)
+ {
+ throw new FileSystemException("vfs.impl/already-inited.error");
+ }
+
+ this.fileCacheStrategy = fileCacheStrategy;
+ }
+
+ /**
+ * Get the cache strategy used.
+ * @return The CacheStrategy.
+ */
+ @Override
+ public CacheStrategy getCacheStrategy()
+ {
+ return fileCacheStrategy;
+ }
+
+ /**
+ * Get the file object decorator used.
+ * @return The decorator.
+ */
+ @Override
+ public Class<?> getFileObjectDecorator()
+ {
+ return fileObjectDecorator;
+ }
+
+ /**
+ * The constructor associated to the fileObjectDecorator.
+ * We cache it here for performance reasons.
+ * @return The decorator's Constructor.
+ */
+ @Override
+ public Constructor<?> getFileObjectDecoratorConst()
+ {
+ return fileObjectDecoratorConst;
+ }
+
+ /**
+ * Set a fileObject decorator to be used for ALL returned file objects.
+ * <p>
+ * Can only be set before the FileSystemManager is initialized.
+ *
+ * @param fileObjectDecorator must be inherted from {@link DecoratedFileObject} a has to provide a
+ * constructor with a single {@link FileObject} as argument
+ * @throws FileSystemException if an error occurs setting the decorator.
+ */
+ public void setFileObjectDecorator(final Class<?> fileObjectDecorator) throws FileSystemException
+ {
+ if (init)
+ {
+ throw new FileSystemException("vfs.impl/already-inited.error");
+ }
+ if (!DecoratedFileObject.class.isAssignableFrom(fileObjectDecorator))
+ {
+ throw new FileSystemException("vfs.impl/invalid-decorator.error", fileObjectDecorator.getName());
+ }
+
+ try
+ {
+ fileObjectDecoratorConst = fileObjectDecorator.getConstructor(new Class[]{FileObject.class});
+ }
+ catch (final NoSuchMethodException e)
+ {
+ throw new FileSystemException("vfs.impl/invalid-decorator.error", fileObjectDecorator.getName(), e);
+ }
+
+ this.fileObjectDecorator = fileObjectDecorator;
+ }
+
+ /**
+ * get the fileContentInfoFactory used to determine the infos of a file
+ * content.
+ * @return The FileContentInfoFactory.
+ */
+ @Override
+ public FileContentInfoFactory getFileContentInfoFactory()
+ {
+ return fileContentInfoFactory;
+ }
+
+ /**
+ * set the fileContentInfoFactory used to determine the infos of a file
+ * content.
+ * <p>
+ * Can only be set before the FileSystemManager is initialized.
+ *
+ * @param fileContentInfoFactory The FileContentInfoFactory.
+ * @throws FileSystemException if an error occurs setting the FileContentInfoFactory.
+ */
+ public void setFileContentInfoFactory(final FileContentInfoFactory fileContentInfoFactory)
+ throws FileSystemException
+ {
+ if (init)
+ {
+ throw new FileSystemException("vfs.impl/already-inited.error");
+ }
+
+ this.fileContentInfoFactory = fileContentInfoFactory;
+ }
+
+ /**
+ * Sets the file replicator to use.
+ * <p>
+ * The manager takes care of all lifecycle management.
+ *
+ * @param replicator The FileReplicator.
+ * @throws FileSystemException if an error occurs setting the replicator.
+ */
+ public void setReplicator(final FileReplicator replicator)
+ throws FileSystemException
+ {
+ setupComponent(replicator);
+ fileReplicator = replicator;
+ }
+
+ /**
+ * Sets the temporary file store to use.
+ * <p>
+ * The manager takes care of all lifecycle management.
+ *
+ * @param tempFileStore The temporary FileStore.
+ * @throws FileSystemException if an error occurs adding the file store.
+ */
+ public void setTemporaryFileStore(final TemporaryFileStore tempFileStore)
+ throws FileSystemException
+ {
+ setupComponent(tempFileStore);
+ this.tempFileStore = tempFileStore;
+ }
+
+ /**
+ * Sets the logger to use.
+ * <p>
+ * This overwrites the default logger for this manager and is not reset in {@link #close()}.
+ *
+ * @param log The Logger to use.
+ */
+ @Override
+ public void setLogger(final Log log)
+ {
+ this.log = log;
+ }
+
+ /**
+ * Initializes a component, if it has not already been initialised.
+ *
+ * @param component The component to setup.
+ * @throws FileSystemException if an error occurs.
+ */
+ private void setupComponent(final Object component)
+ throws FileSystemException
+ {
+ if (!components.contains(component))
+ {
+ if (component instanceof VfsComponent)
+ {
+ final VfsComponent vfsComponent = (VfsComponent) component;
+ vfsComponent.setLogger(getLogger());
+ vfsComponent.setContext(context);
+ vfsComponent.init();
+ }
+ components.add(component);
+ }
+ }
+
+ /**
+ * Closes a component, if it has not already been closed.
+ *
+ * @param component The component to close.
+ */
+ private void closeComponent(final Object component)
+ {
+ if (component != null && components.contains(component))
+ {
+ if (component instanceof VfsComponent)
+ {
+ final VfsComponent vfsComponent = (VfsComponent) component;
+ vfsComponent.close();
+ }
+ components.remove(component);
+ }
+ }
+
+ /**
+ * Returns the file replicator.
+ *
+ * @return The file replicator. Never returns null.
+ * @throws FileSystemException if there is no FileReplicator.
+ */
+ public FileReplicator getReplicator() throws FileSystemException
+ {
+ if (fileReplicator == null)
+ {
+ throw new FileSystemException("vfs.impl/no-replicator.error");
+ }
+ return fileReplicator;
+ }
+
+ /**
+ * Returns the temporary file store.
+ *
+ * @return The file store. Never returns null.
+ * @throws FileSystemException if there is no TemporaryFileStore.
+ */
+ public TemporaryFileStore getTemporaryFileStore()
+ throws FileSystemException
+ {
+ if (tempFileStore == null)
+ {
+ throw new FileSystemException("vfs.impl/no-temp-file-store.error");
+ }
+ return tempFileStore;
+ }
+
+ /**
+ * Initializes this manager.
+ * <p>
+ * If no value for the following properties was specified, it will
+ * use the following defaults:
+ * <ul>
+ * <li>fileContentInfoFactory = new FileContentInfoFilenameFactory()</li>
+ * <li>filesCache = new SoftRefFilesCache()</li>
+ * <li>fileCacheStrategy = CacheStrategy.ON_RESOLVE</li>
+ * </ul>
+ *
+ * @throws FileSystemException if an error occurs during initialization.
+ */
+ public void init() throws FileSystemException
+ {
+ if (fileContentInfoFactory == null)
+ {
+ fileContentInfoFactory = new FileContentInfoFilenameFactory();
+ }
+
+ if (filesCache == null)
+ {
+ // filesCache = new DefaultFilesCache();
+ filesCache = new SoftRefFilesCache();
+ }
+ if (fileCacheStrategy == null)
+ {
+ fileCacheStrategy = CacheStrategy.ON_RESOLVE;
+ }
+ setupComponent(filesCache);
+
+ vfsProvider = new VirtualFileProvider();
+ setupComponent(vfsProvider);
+
+ init = true;
+ }
+
+ /**
+ * Closes the manager.
+ * <p>
+ * This will close all providers (all files), it will also close
+ * all managed components including temporary files, replicator,
+ * file cache and file operations.
+ * <p>
+ * The manager is in uninitialized state after this method.
+ */
+ public void close()
+ {
+ if (!init)
+ {
+ return;
+ }
+
+ // make sure all discovered components in
+ // org.apache.commons.vfs2.impl.StandardFileSystemManager.configure(Element)
+ // are closed here
+
+ // Close the file system providers.
+ for (final FileProvider provider : providers.values())
+ {
+ closeComponent(provider);
+ }
+ // unregister all
+ providers.clear();
+
+ // Close the other components
+ closeComponent(vfsProvider);
+ closeComponent(fileReplicator);
+ closeComponent(tempFileStore);
+ closeComponent(filesCache);
+ closeComponent(defaultProvider);
+
+ // FileOperations are components, too
+ for (final List<FileOperationProvider> opproviders : operationProviders.values())
+ {
+ for (final FileOperationProvider p : opproviders)
+ {
+ closeComponent(p);
+ }
+ }
+ // unregister all
+ operationProviders.clear();
+
+ // collections with add()
+ typeMap.clear();
+
+ // should not happen, but make debugging easier:
+ if (!components.isEmpty())
+ {
+ log.warn("DefaultFilesystemManager.close: not all components are closed: " + components.toString());
+ }
+ components.clear();
+
+ // managed components
+ vfsProvider = null;
+
+ // setters and derived state
+ defaultProvider = null;
+ baseFile = null;
+ fileObjectDecorator = null;
+ fileObjectDecoratorConst = null;
+ localFileProvider = null;
+ fileReplicator = null;
+ tempFileStore = null;
+ // setters with init() defaults
+ filesCache = null;
+ fileCacheStrategy = null;
+ fileContentInfoFactory = null;
+
+ init = false;
+ }
+
+ /**
+ * Free all resources used by unused filesystems created by this manager.
+ */
+ public void freeUnusedResources()
+ {
+ if (!init)
+ {
+ return;
+ }
+
+ // Close the providers.
+ for (final FileProvider fileProvider : providers.values())
+ {
+ final AbstractFileProvider provider = (AbstractFileProvider) fileProvider;
+ provider.freeUnusedResources();
+ }
+ // vfsProvider does not need to free resources
+ }
+
+ /**
+ * Sets the base file to use when resolving relative URI.
+ * @param baseFile The new base FileObject.
+ * @throws FileSystemException if an error occurs.
+ */
+ public void setBaseFile(final FileObject baseFile)
+ throws FileSystemException
+ {
+ this.baseFile = baseFile;
+ }
+
+ /**
+ * Sets the base file to use when resolving relative URI.
+ * @param baseFile The new base FileObject.
+ * @throws FileSystemException if an error occurs.
+ */
+ public void setBaseFile(final File baseFile) throws FileSystemException
+ {
+ this.baseFile = getLocalFileProvider().findLocalFile(baseFile);
+ }
+
+ /**
+ * Returns the base file used to resolve relative URI.
+ * @return The FileObject that represents the base file.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileObject getBaseFile() throws FileSystemException
+ {
+ return baseFile;
+ }
+
+ /**
+ * Locates a file by URI.
+ * @param uri The URI of the file to locate.
+ * @return The FileObject for the located file.
+ * @throws FileSystemException if the file cannot be located or an error occurs.
+ */
+ @Override
+ public FileObject resolveFile(final String uri) throws FileSystemException
+ {
+ return resolveFile(getBaseFile(), uri);
+ }
+
+ /**
+ * Locate a file by URI, use the FileSystemOptions for file-system creation.
+ * @param uri The URI of the file to locate.
+ * @param fileSystemOptions The options for the FileSystem.
+ * @return The FileObject for the located file.
+ * @throws FileSystemException if the file cannot be located or an error occurs.
+ */
+
+ @Override
+ public FileObject resolveFile(final String uri,
+ final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ // return resolveFile(baseFile, uri, fileSystemOptions);
+ return resolveFile(getBaseFile(), uri, fileSystemOptions);
+ }
+
+ /**
+ * Resolves a URI, relative to base file.
+ * <p>
+ * Uses the {@linkplain #getLocalFileProvider() local file provider} to
+ * locate the system file.
+ *
+ * @param baseFile The base File to use to locate the file.
+ * @param uri The URI of the file to locate.
+ * @return The FileObject for the located file.
+ * @throws FileSystemException if the file cannot be located or an error occurs.
+ */
+ @Override
+ public FileObject resolveFile(final File baseFile, final String uri)
+ throws FileSystemException
+ {
+ final FileObject baseFileObj = getLocalFileProvider().findLocalFile(
+ baseFile);
+ return resolveFile(baseFileObj, uri);
+ }
+
+ /**
+ * Resolves a URI, relative to a base file.
+ * @param baseFile The base FileOjbect to use to locate the file.
+ * @param uri The URI of the file to locate.
+ * @return The FileObject for the located file.
+ * @throws FileSystemException if the file cannot be located or an error occurs.
+ */
+ @Override
+ public FileObject resolveFile(final FileObject baseFile, final String uri)
+ throws FileSystemException
+ {
+ return resolveFile(baseFile, uri, baseFile == null ? null : baseFile
+ .getFileSystem().getFileSystemOptions());
+ }
+
+ /**
+ * Resolves a URI, relative to a base file with specified FileSystem
+ * configuration.
+ * @param baseFile The base file.
+ * @param uri The file name. May be a fully qualified or relative path or a url.
+ * @param fileSystemOptions Options to pass to the file system.
+ * @return A FileObject representing the target file.
+ * @throws FileSystemException if an error occurs accessing the file.
+ */
+ public FileObject resolveFile(final FileObject baseFile, final String uri,
+ final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ final FileObject realBaseFile;
+ if (baseFile != null && VFS.isUriStyle()
+ && baseFile.getName().isFile())
+ {
+ realBaseFile = baseFile.getParent();
+ }
+ else
+ {
+ realBaseFile = baseFile;
+ }
+ // TODO: use resolveName and use this name to resolve the fileObject
+
+ UriParser.checkUriEncoding(uri);
+
+ if (uri == null)
+ {
+ throw new IllegalArgumentException();
+ }
+
+ // Extract the scheme
+ final String scheme = UriParser.extractScheme(uri);
+ if (scheme != null)
+ {
+ // An absolute URI - locate the provider
+ final FileProvider provider = providers.get(scheme);
+ if (provider != null)
+ {
+ return provider.findFile(realBaseFile, uri, fileSystemOptions);
+ }
+ // Otherwise, assume a local file
+ }
+
+ // Handle absolute file names
+ if (localFileProvider != null
+ && localFileProvider.isAbsoluteLocalName(uri))
+ {
+ return localFileProvider.findLocalFile(uri);
+ }
+
+ if (scheme != null)
+ {
+ // An unknown scheme - hand it to the default provider
+ if (defaultProvider == null)
+ {
+ throw new FileSystemException("vfs.impl/unknown-scheme.error", scheme, uri);
+ }
+ return defaultProvider.findFile(realBaseFile, uri, fileSystemOptions);
+ }
+
+ // Assume a relative name - use the supplied base file
+ if (realBaseFile == null)
+ {
+ throw new FileSystemException("vfs.impl/find-rel-file.error", uri);
+ }
+
+ return realBaseFile.resolveFile(uri);
+ }
+
+ /**
+ * Resolves a name, relative to the file. If the supplied name is an
+ * absolute path, then it is resolved relative to the root of the file
+ * system that the file belongs to. If a relative name is supplied, then it
+ * is resolved relative to this file name.
+ * @param root The base FileName.
+ * @param path The path to the file relative to the base FileName or an absolute path.
+ * @return The constructed FileName.
+ * @throws FileSystemException if an error occurs constructing the FileName.
+ */
+ @Override
+ public FileName resolveName(final FileName root, final String path)
+ throws FileSystemException
+ {
+ return resolveName(root, path, NameScope.FILE_SYSTEM);
+ }
+
+ /**
+ * Resolves a name, relative to the root.
+ *
+ * @param base the base filename
+ * @param name the name
+ * @param scope the {@link NameScope}
+ * @return The FileName of the file.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileName resolveName(final FileName base, final String name,
+ final NameScope scope) throws FileSystemException
+ {
+ final FileName realBase;
+ if (base != null && VFS.isUriStyle() && base.isFile())
+ {
+ realBase = base.getParent();
+ }
+ else
+ {
+ realBase = base;
+ }
+
+ final StringBuilder buffer = new StringBuilder(name);
+
+ // Adjust separators
+ UriParser.fixSeparators(buffer);
+ String scheme = UriParser.extractScheme(buffer.toString());
+
+ // Determine whether to prepend the base path
+ if (name.length() == 0 || (scheme == null && buffer.charAt(0) != FileName.SEPARATOR_CHAR))
+ {
+ // Supplied path is not absolute
+ if (!VFS.isUriStyle())
+ {
+ // when using uris the parent already do have the trailing "/"
+ buffer.insert(0, FileName.SEPARATOR_CHAR);
+ }
+ buffer.insert(0, realBase.getPath());
+ }
+
+ // Normalise the path
+ final FileType fileType = UriParser.normalisePath(buffer);
+
+ // Check the name is ok
+ final String resolvedPath = buffer.toString();
+ if (!AbstractFileName
+ .checkName(realBase.getPath(), resolvedPath, scope))
+ {
+ throw new FileSystemException(
+ "vfs.provider/invalid-descendent-name.error", name);
+ }
+
+ String fullPath;
+ if (scheme != null)
+ {
+ fullPath = resolvedPath;
+ }
+ else
+ {
+ scheme = realBase.getScheme();
+ fullPath = realBase.getRootURI() + resolvedPath;
+ }
+ final FileProvider provider = providers.get(scheme);
+ if (provider != null)
+ {
+ // TODO: extend the filename parser to be able to parse
+ // only a pathname and take the missing informations from
+ // the base. Then we can get rid of the string operation.
+ // // String fullPath = base.getRootURI() +
+ // resolvedPath.substring(1);
+
+ return provider.parseUri(realBase, fullPath);
+ }
+
+ // An unknown scheme - hand it to the default provider - if possible
+ if (scheme != null && defaultProvider != null)
+ {
+ return defaultProvider.parseUri(realBase, fullPath);
+ }
+
+ // TODO: avoid fallback to this point
+ // this happens if we have a virtual filesystem (no provider for scheme)
+ return ((AbstractFileName) realBase).createName(resolvedPath, fileType);
+ }
+
+ /**
+ * Resolve the uri to a filename.
+ * @param uri The URI to resolve.
+ * @return The FileName of the file.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileName resolveURI(final String uri) throws FileSystemException
+ {
+ UriParser.checkUriEncoding(uri);
+
+ if (uri == null)
+ {
+ throw new IllegalArgumentException();
+ }
+
+ // Extract the scheme
+ final String scheme = UriParser.extractScheme(uri);
+ if (scheme != null)
+ {
+ // An absolute URI - locate the provider
+ final FileProvider provider = providers.get(scheme);
+ if (provider != null)
+ {
+ return provider.parseUri(null, uri);
+ }
+
+ // Otherwise, assume a local file
+ }
+
+ // Handle absolute file names
+ if (localFileProvider != null
+ && localFileProvider.isAbsoluteLocalName(uri))
+ {
+ return localFileProvider.parseUri(null, uri);
+ }
+
+ if (scheme != null)
+ {
+ // An unknown scheme - hand it to the default provider
+ if (defaultProvider == null)
+ {
+ throw new FileSystemException("vfs.impl/unknown-scheme.error", scheme, uri);
+ }
+ return defaultProvider.parseUri(null, uri);
+ }
+
+ // Assume a relative name - use the supplied base file
+ if (baseFile == null)
+ {
+ throw new FileSystemException("vfs.impl/find-rel-file.error", uri);
+ }
+
+ return resolveName(baseFile.getName(), uri, NameScope.FILE_SYSTEM);
+ }
+
+ /**
+ * Converts a local file into a {@link FileObject}.
+ * @param file The input File.
+ * @return the create FileObject
+ * @throws FileSystemException if an error occurs creating the file.
+ */
+ @Override
+ public FileObject toFileObject(final File file) throws FileSystemException
+ {
+ return getLocalFileProvider().findLocalFile(file);
+ }
+
+ /**
+ * Creates a layered file system.
+ * @param scheme The scheme to use.
+ * @param file The FileObject.
+ * @return The layered FileObject.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileObject createFileSystem(final String scheme,
+ final FileObject file) throws FileSystemException
+ {
+ final FileProvider provider = providers.get(scheme);
+ if (provider == null)
+ {
+ throw new FileSystemException("vfs.impl/unknown-provider.error", scheme, file);
+ }
+ return provider.createFileSystem(scheme, file, file.getFileSystem().getFileSystemOptions());
+ }
+
+ /**
+ * Creates a layered file system.
+ * @param file The FileObject to use.
+ * @return The layered FileObject.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileObject createFileSystem(final FileObject file)
+ throws FileSystemException
+ {
+ final String scheme = typeMap.getScheme(file);
+ if (scheme == null)
+ {
+ throw new FileSystemException(
+ "vfs.impl/no-provider-for-file.error", file);
+ }
+
+ return createFileSystem(scheme, file);
+ }
+
+ /**
+ * Determines if a layered file system can be created for a given file.
+ *
+ * @param file The file to check for.
+ * @return true if the FileSystem can be created.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public boolean canCreateFileSystem(final FileObject file)
+ throws FileSystemException
+ {
+ return typeMap.getScheme(file) != null;
+ }
+
+ /**
+ * Creates a virtual file system.
+ * @param rootFile The FileObject to use.
+ * @return The FileObject in the VirtualFileSystem.
+ * @throws FileSystemException if an error occurs creating the file.
+ */
+ @Override
+ public FileObject createVirtualFileSystem(final FileObject rootFile)
+ throws FileSystemException
+ {
+ return vfsProvider.createFileSystem(rootFile);
+ }
+
+ /**
+ * Creates an empty virtual file system.
+ * @param rootUri The URI to use as the root of the FileSystem.
+ * @return A FileObject in the virtual FileSystem.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileObject createVirtualFileSystem(final String rootUri)
+ throws FileSystemException
+ {
+ return vfsProvider.createFileSystem(rootUri);
+ }
+
+ /**
+ * Locates the local file provider.
+ * <p>
+ * The local file provider is the first
+ * {@linkplain #addProvider(String[], FileProvider) provider added}
+ * implementing {@link LocalFileProvider}.
+ *
+ * @return The LocalFileProvider.
+ * @throws FileSystemException if no local file provider was set.
+ */
+ private LocalFileProvider getLocalFileProvider() throws FileSystemException
+ {
+ if (localFileProvider == null)
+ {
+ throw new FileSystemException(
+ "vfs.impl/no-local-file-provider.error");
+ }
+ return localFileProvider;
+ }
+
+ /**
+ * Get the URLStreamHandlerFactory.
+ * @return The URLStreamHandlerFactory.
+ */
+ @Override
+ public URLStreamHandlerFactory getURLStreamHandlerFactory()
+ {
+ return new VfsStreamHandlerFactory();
+ }
+
+ /**
+ * Closes the given filesystem.
+ * <p>
+ * If you use VFS as singleton it is VERY dangerous to call this method.
+ *
+ * @param filesystem The FileSystem to close.
+ */
+ @Override
+ public void closeFileSystem(final FileSystem filesystem)
+ {
+ // inform the cache ...
+ getFilesCache().clear(filesystem);
+
+ // just in case the cache didnt call _closeFileSystem
+ _closeFileSystem(filesystem);
+ }
+
+ /**
+ * Closes the given file system.
+ * <p>
+ * If you use VFS as singleton it is VERY dangerous to call this method
+ * </p>
+ *
+ * @param filesystem The FileSystem to close.
+ */
+ public void _closeFileSystem(final FileSystem filesystem)
+ {
+ final FileProvider provider = providers.get(filesystem.getRootName().getScheme());
+ if (provider != null)
+ {
+ ((AbstractFileProvider) provider).closeFileSystem(filesystem);
+ }
+ else if (filesystem instanceof VirtualFileSystem)
+ {
+ // vfsProvider does not implement AbstractFileProvider
+ vfsProvider.closeFileSystem(filesystem);
+ }
+ }
+
+ /**
+ * This is an internal class because it needs access to the private member
+ * providers.
+ */
+ final class VfsStreamHandlerFactory implements URLStreamHandlerFactory
+ {
+ @Override
+ public URLStreamHandler createURLStreamHandler(final String protocol)
+ {
+ final FileProvider provider = providers.get(protocol);
+ if (provider != null)
+ {
+ return new DefaultURLStreamHandler(context);
+ }
+
+ // Route all other calls to the default URLStreamHandlerFactory
+ return new URLStreamHandlerProxy();
+ }
+ }
+
+ /**
+ * Get the schemes currently available.
+ * @return The array of scheme names.
+ */
+ @Override
+ public String[] getSchemes()
+ {
+ final String[] schemes = new String[providers.size()];
+ providers.keySet().toArray(schemes);
+ return schemes;
+ }
+
+ /**
+ * Get the capabilities for a given scheme.
+ *
+ * @param scheme The scheme to located.
+ * @return A Collection of capabilities.
+ * @throws FileSystemException if the given scheme is not konwn
+ */
+ @Override
+ public Collection<Capability> getProviderCapabilities(final String scheme)
+ throws FileSystemException
+ {
+ final FileProvider provider = providers.get(scheme);
+ if (provider == null)
+ {
+ throw new FileSystemException("vfs.impl/unknown-scheme.error", scheme);
+ }
+
+ return provider.getCapabilities();
+ }
+
+ /**
+ * Get the configuration builder for the given scheme.
+ * @param scheme The scheme to locate.
+ * @return The FileSystemConfigBuilder for the scheme.
+ * @throws FileSystemException if the given scheme is not konwn
+ */
+ @Override
+ public FileSystemConfigBuilder getFileSystemConfigBuilder(final String scheme)
+ throws FileSystemException
+ {
+ final FileProvider provider = providers.get(scheme);
+ if (provider == null)
+ {
+ throw new FileSystemException("vfs.impl/unknown-scheme.error", scheme);
+ }
+
+ return provider.getConfigBuilder();
+ }
+
+ // -- OPERATIONS --
+
+ /**
+ * Adds the specified FileOperationProvider for the specified scheme.
+ * Several FileOperationProvider's might be registered for the same scheme.
+ * For example, for "file" scheme we can register SvnWsOperationProvider and
+ * CvsOperationProvider.
+ *
+ * @param scheme The scheme the provider should be registered for.
+ * @param operationProvider The FileOperationProvider.
+ * @throws FileSystemException if an error occurs adding the provider.
+ */
+ @Override
+ public void addOperationProvider(final String scheme,
+ final FileOperationProvider operationProvider)
+ throws FileSystemException
+ {
+ addOperationProvider(new String[] {scheme}, operationProvider);
+ }
+
+ /**
+ * @see FileSystemManager#addOperationProvider(String,
+ * org.apache.commons.vfs2.operations.FileOperationProvider)
+ *
+ * @param schemes The array of schemes the provider should apply to.
+ * @param operationProvider The FileOperationProvider.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public void addOperationProvider(final String[] schemes,
+ final FileOperationProvider operationProvider)
+ throws FileSystemException
+ {
+ for (final String scheme : schemes)
+ {
+ if (!operationProviders.containsKey(scheme))
+ {
+ final List<FileOperationProvider> providers = new ArrayList<FileOperationProvider>();
+ operationProviders.put(scheme, providers);
+ }
+
+ final List<FileOperationProvider> providers = operationProviders.get(scheme);
+
+ if (providers.contains(operationProvider))
+ {
+ throw new FileSystemException(
+ "vfs.operation/operation-provider-already-added.error", scheme);
+ }
+
+ setupComponent(operationProvider);
+
+ providers.add(operationProvider);
+ }
+ }
+
+ /**
+ * @param scheme
+ * the scheme for wich we want to get the list af registered
+ * providers.
+ *
+ * @return the registered FileOperationProviders for the specified scheme.
+ * If there were no providers registered for the scheme, it returns
+ * null.
+ *
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileOperationProvider[] getOperationProviders(final String scheme)
+ throws FileSystemException
+ {
+
+ final List<?> providers = operationProviders.get(scheme);
+ if (providers == null || providers.size() == 0)
+ {
+ return null;
+ }
+ return providers.toArray(new FileOperationProvider[] {});
+ }
+
+ /**
+ * Converts a URI into a {@link FileObject}.
+ *
+ * @param uri The URI to convert.
+ * @return The {@link FileObject} that represents the URI. Never
+ * returns null.
+ * @throws FileSystemException On error converting the URI.
+ * @since 2.1
+ */
+ @Override
+ public FileObject resolveFile(final URI uri) throws FileSystemException
+ {
+ // TODO Push the URI deeper into VFS
+ return resolveFile(baseFile, uri.toString(), null);
+ }
+
+ /**
+ * Converts a URL into a {@link FileObject}.
+ *
+ * @param url The URL to convert.
+ * @return The {@link FileObject} that represents the URL. Never
+ * returns null.
+ * @throws FileSystemException On error converting the URL.
+ * @since 2.1
+ */
+ @Override
+ public FileObject resolveFile(final URL url) throws FileSystemException
+ {
+ try
+ {
+ return this.resolveFile(url.toURI());
+ }
+ catch (final URISyntaxException e)
+ {
+ throw new FileSystemException(e);
+ }
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DefaultProviderConfiguration.java b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DefaultProviderConfiguration.java
new file mode 100644
index 0000000..068b8a2
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DefaultProviderConfiguration.java
@@ -0,0 +1,30 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.impl;
+
+
+/**
+ * Same as {@link ProviderConfiguration} but for the default provider.
+ */
+public class DefaultProviderConfiguration extends ProviderConfiguration
+{
+ @Override
+ public boolean isDefault()
+ {
+ return true;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DefaultVfsComponentContext.java b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DefaultVfsComponentContext.java
new file mode 100644
index 0000000..9aed70c
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/DefaultVfsComponentContext.java
@@ -0,0 +1,109 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.impl;
+
+import java.io.File;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.FileReplicator;
+import org.apache.commons.vfs2.provider.TemporaryFileStore;
+import org.apache.commons.vfs2.provider.VfsComponentContext;
+
+
+/**
+ * The default context implementation.
+ */
+final class DefaultVfsComponentContext
+ implements VfsComponentContext
+{
+ private final DefaultFileSystemManager manager;
+
+ public DefaultVfsComponentContext(final DefaultFileSystemManager manager)
+ {
+ this.manager = manager;
+ }
+
+ /**
+ * Locate a file by name.
+ */
+ @Override
+ public FileObject resolveFile(final FileObject baseFile, final String name,
+ final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ return manager.resolveFile(baseFile, name, fileSystemOptions);
+ }
+
+ /**
+ * Locate a file by name.
+ */
+ @Override
+ public FileObject resolveFile(final String name, final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ return manager.resolveFile(name, fileSystemOptions);
+ }
+
+ @Override
+ public FileName parseURI(final String uri) throws FileSystemException
+ {
+ return manager.resolveURI(uri);
+ }
+
+ /**
+ * Returns a {@link FileObject} for a local file.
+ */
+ @Override
+ public FileObject toFileObject(final File file)
+ throws FileSystemException
+ {
+ return manager.toFileObject(file);
+ }
+
+ /**
+ * Locates a file replicator for the provider to use.
+ */
+ @Override
+ public FileReplicator getReplicator() throws FileSystemException
+ {
+ return manager.getReplicator();
+ }
+
+ /**
+ * Locates a temporary file store for the provider to use.
+ */
+ @Override
+ public TemporaryFileStore getTemporaryFileStore() throws FileSystemException
+ {
+ return manager.getTemporaryFileStore();
+ }
+
+ /**
+ * Returns the filesystem manager for the current context
+ *
+ * @return the filesystem manager
+ */
+ @Override
+ public FileSystemManager getFileSystemManager()
+ {
+ return manager;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/impl/FileContentInfoFilenameFactory.java b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/FileContentInfoFilenameFactory.java
new file mode 100644
index 0000000..977a253
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/FileContentInfoFilenameFactory.java
@@ -0,0 +1,48 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.impl;
+
+import java.net.FileNameMap;
+import java.net.URLConnection;
+
+import org.apache.commons.vfs2.FileContent;
+import org.apache.commons.vfs2.FileContentInfo;
+import org.apache.commons.vfs2.FileContentInfoFactory;
+
+/**
+ * The FileContentInfoFilenameFactory.
+ * <p>
+ * Uses the filename extension to determine the content-type.
+ * The content-encoding is not resolved.
+ */
+public class FileContentInfoFilenameFactory implements FileContentInfoFactory
+{
+ @Override
+ public FileContentInfo create(final FileContent fileContent)
+ {
+ String contentType = null;
+
+ final String name = fileContent.getFile().getName().getBaseName();
+ if (name != null)
+ {
+ final FileNameMap fileNameMap = URLConnection.getFileNameMap();
+ contentType = fileNameMap.getContentTypeFor(name);
+ }
+
+ return new DefaultFileContentInfo(contentType, null);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/impl/FileTypeMap.java b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/FileTypeMap.java
new file mode 100644
index 0000000..eefda12
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/FileTypeMap.java
@@ -0,0 +1,83 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.impl;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.commons.vfs2.FileContent;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+
+/**
+ * A helper class that determines the provider to use for a file.
+ */
+class FileTypeMap
+{
+ private final Map<String, String> mimeTypeMap = new HashMap<String, String>();
+ private final Map<String, String> extensionMap = new HashMap<String, String>();
+
+ /**
+ * Adds a MIME type mapping.
+ */
+ public void addMimeType(final String mimeType, final String scheme)
+ {
+ mimeTypeMap.put(mimeType, scheme);
+ }
+
+ /**
+ * Adds a filename extension mapping.
+ */
+ public void addExtension(final String extension, final String scheme)
+ {
+ extensionMap.put(extension, scheme);
+ }
+
+ /**
+ * Find the scheme for the provider of a layered file system.
+ * <p>
+ * This will check the FileContentInfo or file extension.
+ * @return Scheme supporting the file type or null (if unknonw).
+ */
+ public String getScheme(final FileObject file) throws FileSystemException
+ {
+ // Check the file's mime type for a match
+ final FileContent content = file.getContent();
+ final String mimeType = content.getContentInfo().getContentType();
+ if (mimeType != null)
+ {
+ return mimeTypeMap.get(mimeType);
+ }
+
+ // no specific mime-type - if it is a file also check the extension
+ if (!file.isFile())
+ {
+ return null; // VFS-490 folders don't use extensions for mime-type
+ }
+ final String extension = file.getName().getExtension();
+ return extensionMap.get(extension);
+ }
+
+ /**
+ * Removes all extensions and scheme mappings.
+ */
+ public void clear()
+ {
+ mimeTypeMap.clear();
+ extensionMap.clear();
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/impl/PrivilegedFileReplicator.java b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/PrivilegedFileReplicator.java
new file mode 100644
index 0000000..d47cd86
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/PrivilegedFileReplicator.java
@@ -0,0 +1,199 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.impl;
+
+import java.io.File;
+import java.security.AccessController;
+import java.security.PrivilegedAction;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSelector;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.provider.FileReplicator;
+import org.apache.commons.vfs2.provider.VfsComponent;
+import org.apache.commons.vfs2.provider.VfsComponentContext;
+
+/**
+ * A file replicator that wraps another file replicator, performing
+ * the replication as a privileged action.
+ */
+public class PrivilegedFileReplicator
+ implements FileReplicator, VfsComponent
+{
+ private final FileReplicator replicator;
+ private final VfsComponent replicatorComponent;
+
+ public PrivilegedFileReplicator(final FileReplicator replicator)
+ {
+ this.replicator = replicator;
+ if (replicator instanceof VfsComponent)
+ {
+ replicatorComponent = (VfsComponent) replicator;
+ }
+ else
+ {
+ replicatorComponent = null;
+ }
+ }
+
+ /**
+ * Sets the Logger to use for the component.
+ *
+ * @param logger The logger.
+ */
+ @Override
+ public void setLogger(final Log logger)
+ {
+ if (replicatorComponent != null)
+ {
+ replicatorComponent.setLogger(logger);
+ }
+ }
+
+ /**
+ * Sets the context for the replicator.
+ *
+ * @param context The component context.
+ */
+ @Override
+ public void setContext(final VfsComponentContext context)
+ {
+ if (replicatorComponent != null)
+ {
+ replicatorComponent.setContext(context);
+ }
+ }
+
+ /**
+ * Initializes the component.
+ *
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public void init() throws FileSystemException
+ {
+ if (replicatorComponent != null)
+ {
+ try
+ {
+ AccessController.doPrivileged(new InitAction());
+ }
+ catch (final PrivilegedActionException e)
+ {
+ throw new FileSystemException("vfs.impl/init-replicator.error", e);
+ }
+ }
+ }
+
+ /**
+ * Closes the replicator.
+ */
+ @Override
+ public void close()
+ {
+ if (replicatorComponent != null)
+ {
+ AccessController.doPrivileged(new CloseAction());
+ }
+ }
+
+ /**
+ * Creates a local copy of the file, and all its descendants.
+ *
+ * @param srcFile The source FileObject.
+ * @param selector The file selector.
+ * @return The replicated file.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public File replicateFile(final FileObject srcFile, final FileSelector selector)
+ throws FileSystemException
+ {
+ try
+ {
+ final ReplicateAction action = new ReplicateAction(srcFile, selector);
+ return AccessController.doPrivileged(action);
+ }
+ catch (final PrivilegedActionException e)
+ {
+ throw new FileSystemException("vfs.impl/replicate-file.error", e, srcFile.getName());
+ }
+ }
+
+ /**
+ * An action that initialises the wrapped replicator.
+ */
+ private class InitAction implements PrivilegedExceptionAction<Object>
+ {
+ /**
+ * Performs the action.
+ */
+ @Override
+ public Object run() throws Exception
+ {
+ replicatorComponent.init();
+ return null;
+ }
+ }
+
+ /**
+ * An action that replicates a file using the wrapped replicator.
+ */
+ private class ReplicateAction implements PrivilegedExceptionAction<File>
+ {
+ private final FileObject srcFile;
+ private final FileSelector selector;
+
+ public ReplicateAction(final FileObject srcFile,
+ final FileSelector selector)
+ {
+ this.srcFile = srcFile;
+ this.selector = selector;
+ }
+
+ /**
+ * Performs the action.
+ * @throws Exception if an error occurs.
+ */
+ @Override
+ public File run() throws Exception
+ {
+ // TODO - Do not pass the selector through. It is untrusted
+ // TODO - Need to determine which files can be read
+ return replicator.replicateFile(srcFile, selector);
+ }
+ }
+
+ /**
+ * An action that closes the wrapped replicator.
+ */
+ private class CloseAction implements PrivilegedAction<Object>
+ {
+ /**
+ * Performs the action.
+ */
+ @Override
+ public Object run()
+ {
+ replicatorComponent.close();
+ return null;
+ }
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/impl/ProviderConfiguration.java b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/ProviderConfiguration.java
new file mode 100644
index 0000000..69ded20
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/ProviderConfiguration.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.impl;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * This class describes the configuration for a provider.
+ * <p>
+ * Used by digester in StandardFileSystemManager
+ */
+public class ProviderConfiguration
+{
+ private String className;
+ private final List<String> schemes = new ArrayList<String>(10);
+ private final List<String> dependenies = new ArrayList<String>(10);
+
+ public ProviderConfiguration()
+ {
+ }
+
+ public String getClassName()
+ {
+ return className;
+ }
+
+ public void setClassName(final String className)
+ {
+ this.className = className;
+ }
+
+ public void setScheme(final String scheme)
+ {
+ schemes.add(scheme);
+ }
+
+ public List<String> getSchemes()
+ {
+ return schemes;
+ }
+
+ public void setDependency(final String dependency)
+ {
+ dependenies.add(dependency);
+ }
+
+ public List<String> getDependencies()
+ {
+ return dependenies;
+ }
+
+ public boolean isDefault()
+ {
+ return false;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/impl/Resource.java b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/Resource.java
new file mode 100644
index 0000000..6e3ea16
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/Resource.java
@@ -0,0 +1,120 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.impl;
+
+import java.io.IOException;
+import java.net.URL;
+import java.util.jar.Attributes;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileUtil;
+
+/**
+ * Helper class for VFSClassLoader.
+ * This represents a resource loaded with the classloader.
+ *
+ * @see VFSClassLoader
+ */
+class Resource
+{
+ private final FileObject root;
+ private final FileObject resource;
+ private final FileObject packageFolder;
+ private final String packageName;
+
+ /**
+ * Creates a new instance.
+ *
+ * @param root The code source FileObject.
+ * @param resource The resource of the FileObject.
+ */
+ public Resource(final String name,
+ final FileObject root,
+ final FileObject resource)
+ throws FileSystemException
+ {
+ this.root = root;
+ this.resource = resource;
+ packageFolder = resource.getParent();
+ final int pos = name.lastIndexOf('/');
+ if (pos == -1)
+ {
+ packageName = null;
+ }
+ else
+ {
+ packageName = name.substring(0, pos).replace('/', '.');
+ }
+ }
+
+ /**
+ * Returns the URL of the resource.
+ */
+ public URL getURL() throws FileSystemException
+ {
+ return resource.getURL();
+ }
+
+ /**
+ * Returns the name of the package containing the resource.
+ */
+ public String getPackageName()
+ {
+ return packageName;
+ }
+
+ /**
+ * Returns an attribute of the package containing the resource.
+ */
+ public String getPackageAttribute(final Attributes.Name attrName) throws FileSystemException
+ {
+ return (String) packageFolder.getContent().getAttribute(attrName.toString());
+ }
+
+ /**
+ * Returns the folder for the package containing the resource.
+ */
+ public FileObject getPackageFolder()
+ {
+ return packageFolder;
+ }
+
+ /**
+ * Returns the FileObject of the resource.
+ */
+ public FileObject getFileObject()
+ {
+ return resource;
+ }
+
+ /**
+ * Returns the code source as an URL.
+ */
+ public URL getCodeSourceURL() throws FileSystemException
+ {
+ return root.getURL();
+ }
+
+ /**
+ * Returns the data for this resource as a byte array.
+ */
+ public byte[] getBytes() throws IOException
+ {
+ return FileUtil.getContent(resource);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/impl/StandardFileSystemManager.java b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/StandardFileSystemManager.java
new file mode 100644
index 0000000..b7f04c1
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/StandardFileSystemManager.java
@@ -0,0 +1,521 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.impl;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.ArrayList;
+import java.util.Enumeration;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.VfsLog;
+import org.apache.commons.vfs2.operations.FileOperationProvider;
+import org.apache.commons.vfs2.provider.FileProvider;
+import org.apache.commons.vfs2.util.Messages;
+import org.w3c.dom.Element;
+import org.w3c.dom.NodeList;
+
+/**
+ * A {@link org.apache.commons.vfs2.FileSystemManager} that configures itself
+ * from an XML (Default: providers.xml) configuration file.
+ * <p>
+ * Certain providers are only loaded and available if the dependent library is in your
+ * classpath. You have to configure your debugging facility to log "debug" messages to see
+ * if a provider was skipped due to "unresolved externals".
+ */
+public class StandardFileSystemManager
+ extends DefaultFileSystemManager
+{
+ private static final String CONFIG_RESOURCE = "providers.xml";
+ private static final String PLUGIN_CONFIG_RESOURCE = "META-INF/vfs-providers.xml";
+
+ private URL configUri;
+ private ClassLoader classLoader;
+
+ /**
+ * Sets the configuration file for this manager.
+ *
+ * @param configUri The URI for this manager.
+ */
+ public void setConfiguration(final String configUri)
+ {
+ try
+ {
+ setConfiguration(new URL(configUri));
+ }
+ catch (final MalformedURLException e)
+ {
+ getLogger().warn(e.getLocalizedMessage(), e);
+ }
+ }
+
+ /**
+ * Sets the configuration file for this manager.
+ *
+ * @param configUri The URI forthis manager.
+ */
+ public void setConfiguration(final URL configUri)
+ {
+ this.configUri = configUri;
+ }
+
+ /**
+ * Sets the ClassLoader to use to load the providers.
+ * Default is to use the ClassLoader that loaded this class.
+ *
+ * @param classLoader The ClassLoader.
+ */
+ public void setClassLoader(final ClassLoader classLoader)
+ {
+ this.classLoader = classLoader;
+ }
+
+ /**
+ * Initializes this manager. Adds the providers and replicator.
+ *
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public void init() throws FileSystemException
+ {
+ // Set the replicator and temporary file store (use the same component)
+ final DefaultFileReplicator replicator = createDefaultFileReplicator();
+ setReplicator(new PrivilegedFileReplicator(replicator));
+ setTemporaryFileStore(replicator);
+
+ if (configUri == null)
+ {
+ // Use default config
+ final URL url = getClass().getResource(CONFIG_RESOURCE);
+ if (url == null)
+ {
+ throw new FileSystemException("vfs.impl/find-config-file.error", CONFIG_RESOURCE);
+ }
+ configUri = url;
+ }
+
+ configure(configUri);
+ configurePlugins();
+
+ // Initialise super-class
+ super.init();
+ }
+
+ /**
+ * Scans the classpath to find any droped plugin.
+ * <p>
+ * The plugin-description has to be in {@code /META-INF/vfs-providers.xml}.
+ *
+ * @throws FileSystemException if an error occurs.
+ */
+ protected void configurePlugins() throws FileSystemException
+ {
+ Enumeration<URL> enumResources;
+ try
+ {
+ enumResources = loadResources(PLUGIN_CONFIG_RESOURCE);
+ }
+ catch (final IOException e)
+ {
+ throw new FileSystemException(e);
+ }
+
+ while (enumResources.hasMoreElements())
+ {
+ final URL url = enumResources.nextElement();
+ configure(url);
+ }
+ }
+
+ private ClassLoader findClassLoader()
+ {
+ if (classLoader != null)
+ {
+ return classLoader;
+ }
+
+ ClassLoader cl = Thread.currentThread().getContextClassLoader();
+ if (cl == null)
+ {
+ cl = getClass().getClassLoader();
+ }
+
+ return cl;
+ }
+
+ protected DefaultFileReplicator createDefaultFileReplicator()
+ {
+ return new DefaultFileReplicator();
+ }
+
+ /**
+ * Configures this manager from an XML configuration file.
+ *
+ * @param configUri The URI of the configuration.
+ * @throws FileSystemException if an error occus.
+ */
+ private void configure(final URL configUri) throws FileSystemException
+ {
+ InputStream configStream = null;
+ try
+ {
+ // Load up the config
+ // TODO - validate
+ final DocumentBuilder builder = createDocumentBuilder();
+ configStream = configUri.openStream();
+ final Element config = builder.parse(configStream).getDocumentElement();
+
+ configure(config);
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("vfs.impl/load-config.error", configUri.toString(), e);
+ }
+ finally
+ {
+ if (configStream != null)
+ {
+ try
+ {
+ configStream.close();
+ }
+ catch (final IOException e)
+ {
+ getLogger().warn(e.getLocalizedMessage(), e);
+ }
+ }
+ }
+ }
+
+ /**
+ * Configures this manager from an XML configuration file.
+ *
+ * @param configUri The URI of the configuration.
+ * @param configStream An InputStream containing the configuration.
+ * @throws FileSystemException if an error occurs.
+ */
+ @SuppressWarnings("unused")
+ private void configure(final String configUri, final InputStream configStream)
+ throws FileSystemException
+ {
+ try
+ {
+ // Load up the config
+ // TODO - validate
+ final DocumentBuilder builder = createDocumentBuilder();
+ final Element config = builder.parse(configStream).getDocumentElement();
+
+ configure(config);
+
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("vfs.impl/load-config.error", configUri, e);
+ }
+ }
+
+ /**
+ * Configure and create a DocumentBuilder
+ *
+ * @return A DocumentBuilder for the configuration.
+ * @throws ParserConfigurationException if an error occurs.
+ */
+ private DocumentBuilder createDocumentBuilder() throws ParserConfigurationException
+ {
+ final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
+ factory.setIgnoringElementContentWhitespace(true);
+ factory.setIgnoringComments(true);
+ factory.setExpandEntityReferences(true);
+ return factory.newDocumentBuilder();
+ }
+
+ /**
+ * Configures this manager from an parsed XML configuration file
+ *
+ * @param config The configuration Element.
+ * @throws FileSystemException if an error occurs.
+ */
+ private void configure(final Element config) throws FileSystemException
+ {
+ // Add the providers
+ final NodeList providers = config.getElementsByTagName("provider");
+ final int count = providers.getLength();
+ for (int i = 0; i < count; i++)
+ {
+ final Element provider = (Element) providers.item(i);
+ addProvider(provider, false);
+ }
+
+ // Add the operation providers
+ final NodeList operationProviders = config.getElementsByTagName("operationProvider");
+ for (int i = 0; i < operationProviders.getLength(); i++)
+ {
+ final Element operationProvider = (Element) operationProviders.item(i);
+ addOperationProvider(operationProvider);
+ }
+
+ // Add the default provider
+ final NodeList defProviders = config.getElementsByTagName("default-provider");
+ if (defProviders.getLength() > 0)
+ {
+ final Element provider = (Element) defProviders.item(0);
+ addProvider(provider, true);
+ }
+
+ // Add the mime-type maps
+ final NodeList mimeTypes = config.getElementsByTagName("mime-type-map");
+ for (int i = 0; i < mimeTypes.getLength(); i++)
+ {
+ final Element map = (Element) mimeTypes.item(i);
+ addMimeTypeMap(map);
+ }
+
+ // Add the extension maps
+ final NodeList extensions = config.getElementsByTagName("extension-map");
+ for (int i = 0; i < extensions.getLength(); i++)
+ {
+ final Element map = (Element) extensions.item(i);
+ addExtensionMap(map);
+ }
+ }
+
+ /**
+ * Adds an extension map.
+ *
+ * @param map containing the Elements.
+ */
+ private void addExtensionMap(final Element map)
+ {
+ final String extension = map.getAttribute("extension");
+ final String scheme = map.getAttribute("scheme");
+ if (scheme != null && scheme.length() > 0)
+ {
+ addExtensionMap(extension, scheme);
+ }
+ }
+
+ /**
+ * Adds a mime-type map.
+ *
+ * @param map containing the Elements.
+ */
+ private void addMimeTypeMap(final Element map)
+ {
+ final String mimeType = map.getAttribute("mime-type");
+ final String scheme = map.getAttribute("scheme");
+ addMimeTypeMap(mimeType, scheme);
+ }
+
+ /**
+ * Adds a provider from a provider definition.
+ *
+ * @param providerDef the provider definition
+ * @param isDefault true if the default should be used.
+ * @throws FileSystemException if an error occurs.
+ */
+ private void addProvider(final Element providerDef, final boolean isDefault)
+ throws FileSystemException
+ {
+ final String classname = providerDef.getAttribute("class-name");
+
+ // Make sure all required schemes are available
+ final String[] requiredSchemes = getRequiredSchemes(providerDef);
+ for (final String requiredScheme : requiredSchemes)
+ {
+ if (!hasProvider(requiredScheme))
+ {
+ final String msg = Messages.getString("vfs.impl/skipping-provider-scheme.debug",
+ classname, requiredScheme);
+ VfsLog.debug(getLogger(), getLogger(), msg);
+ return;
+ }
+ }
+
+ // Make sure all required classes are in classpath
+ final String[] requiredClasses = getRequiredClasses(providerDef);
+ for (final String requiredClass : requiredClasses)
+ {
+ if (!findClass(requiredClass))
+ {
+ final String msg = Messages.getString("vfs.impl/skipping-provider.debug",
+ classname, requiredClass);
+ VfsLog.debug(getLogger(), getLogger(), msg);
+ return;
+ }
+ }
+
+ // Create and register the provider
+ final FileProvider provider = (FileProvider) createInstance(classname);
+ final String[] schemas = getSchemas(providerDef);
+ if (schemas.length > 0)
+ {
+ addProvider(schemas, provider);
+ }
+
+ // Set as default, if required
+ if (isDefault)
+ {
+ setDefaultProvider(provider);
+ }
+ }
+
+ /**
+ * Adds a operationProvider from a operationProvider definition.
+ */
+ private void addOperationProvider(final Element providerDef) throws FileSystemException
+ {
+ final String classname = providerDef.getAttribute("class-name");
+
+ // Attach only to available schemas
+ final String[] schemas = getSchemas(providerDef);
+ for (final String schema : schemas)
+ {
+ if (hasProvider(schema))
+ {
+ final FileOperationProvider operationProvider = (FileOperationProvider) createInstance(classname);
+ addOperationProvider(schema, operationProvider);
+ }
+ }
+ }
+
+ /**
+ * Tests if a class is available.
+ */
+ private boolean findClass(final String className)
+ {
+ try
+ {
+ loadClass(className);
+ return true;
+ }
+ catch (final ClassNotFoundException e)
+ {
+ return false;
+ }
+ }
+
+ /**
+ * Extracts the required classes from a provider definition.
+ */
+ private String[] getRequiredClasses(final Element providerDef)
+ {
+ final ArrayList<String> classes = new ArrayList<String>();
+ final NodeList deps = providerDef.getElementsByTagName("if-available");
+ final int count = deps.getLength();
+ for (int i = 0; i < count; i++)
+ {
+ final Element dep = (Element) deps.item(i);
+ final String className = dep.getAttribute("class-name");
+ if (className != null && className.length() > 0)
+ {
+ classes.add(className);
+ }
+ }
+ return classes.toArray(new String[classes.size()]);
+ }
+
+ /**
+ * Extracts the required schemes from a provider definition.
+ */
+ private String[] getRequiredSchemes(final Element providerDef)
+ {
+ final ArrayList<String> schemes = new ArrayList<String>();
+ final NodeList deps = providerDef.getElementsByTagName("if-available");
+ final int count = deps.getLength();
+ for (int i = 0; i < count; i++)
+ {
+ final Element dep = (Element) deps.item(i);
+ final String scheme = dep.getAttribute("scheme");
+ if (scheme != null && scheme.length() > 0)
+ {
+ schemes.add(scheme);
+ }
+ }
+ return schemes.toArray(new String[schemes.size()]);
+ }
+
+ /**
+ * Extracts the schema names from a provider definition.
+ */
+ private String[] getSchemas(final Element provider)
+ {
+ final ArrayList<String> schemas = new ArrayList<String>();
+ final NodeList schemaElements = provider.getElementsByTagName("scheme");
+ final int count = schemaElements.getLength();
+ for (int i = 0; i < count; i++)
+ {
+ final Element scheme = (Element) schemaElements.item(i);
+ schemas.add(scheme.getAttribute("name"));
+ }
+ return schemas.toArray(new String[schemas.size()]);
+ }
+
+ /**
+ * Creates a provider.
+ */
+ private Object createInstance(final String className)
+ throws FileSystemException
+ {
+ try
+ {
+ Class<?> clazz = loadClass(className);
+ return clazz.newInstance();
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("vfs.impl/create-provider.error", className, e);
+ }
+ }
+
+ /**
+ * Load a class from different class loaders.
+ * @throws ClassNotFoundException if last {@code loadClass} failed.
+ * @see #findClassLoader()
+ */
+ private Class< ? > loadClass(String className) throws ClassNotFoundException
+ {
+ try
+ {
+ return findClassLoader().loadClass(className);
+ }
+ catch (final ClassNotFoundException e)
+ {
+ return getClass().getClassLoader().loadClass(className);
+ }
+ }
+
+ /**
+ * Resolve resources from different class loaders.
+ * @throws IOException if {@code getResource} failed.
+ * @see #findClassLoader()
+ */
+ private Enumeration<URL> loadResources(String name) throws IOException
+ {
+ Enumeration<URL> res = findClassLoader().getResources(name);
+ if (res == null || !res.hasMoreElements())
+ {
+ res = getClass().getClassLoader().getResources(name);
+ }
+ return res;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/impl/SynchronizedFileObject.java b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/SynchronizedFileObject.java
new file mode 100644
index 0000000..a65023f
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/SynchronizedFileObject.java
@@ -0,0 +1,245 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.impl;
+
+import java.util.List;
+
+import org.apache.commons.vfs2.FileContent;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSelector;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.NameScope;
+
+/**
+ * This decorator synchronize all access to the FileObject.
+ */
+public class SynchronizedFileObject extends DecoratedFileObject
+{
+ public SynchronizedFileObject(final FileObject fileObject)
+ {
+ super(fileObject);
+ }
+
+ @Override
+ public void close() throws FileSystemException
+ {
+ synchronized (this)
+ {
+ super.close();
+ }
+ }
+
+ @Override
+ public void copyFrom(final FileObject srcFile, final FileSelector selector) throws FileSystemException
+ {
+ synchronized (this)
+ {
+ super.copyFrom(srcFile, selector);
+ }
+ }
+
+ @Override
+ public void createFile() throws FileSystemException
+ {
+ synchronized (this)
+ {
+ super.createFile();
+ }
+ }
+
+ @Override
+ public void createFolder() throws FileSystemException
+ {
+ synchronized (this)
+ {
+ super.createFolder();
+ }
+ }
+
+ @Override
+ public boolean delete() throws FileSystemException
+ {
+ synchronized (this)
+ {
+ return super.delete();
+ }
+ }
+
+ @Override
+ public int delete(final FileSelector selector) throws FileSystemException
+ {
+ synchronized (this)
+ {
+ return super.delete(selector);
+ }
+ }
+
+ @Override
+ public boolean exists() throws FileSystemException
+ {
+ synchronized (this)
+ {
+ return super.exists();
+ }
+ }
+
+ @Override
+ public void findFiles(final FileSelector selector, final boolean depthwise, final List<FileObject> selected)
+ throws FileSystemException
+ {
+ synchronized (this)
+ {
+ super.findFiles(selector, depthwise, selected);
+ }
+ }
+
+ @Override
+ public FileObject[] findFiles(final FileSelector selector) throws FileSystemException
+ {
+ synchronized (this)
+ {
+ return super.findFiles(selector);
+ }
+ }
+
+ @Override
+ public FileObject getChild(final String name) throws FileSystemException
+ {
+ synchronized (this)
+ {
+ return super.getChild(name);
+ }
+ }
+
+ @Override
+ public FileObject[] getChildren() throws FileSystemException
+ {
+ synchronized (this)
+ {
+ return super.getChildren();
+ }
+ }
+
+ @Override
+ public FileContent getContent() throws FileSystemException
+ {
+ synchronized (this)
+ {
+ return super.getContent();
+ }
+ }
+
+ @Override
+ public FileType getType() throws FileSystemException
+ {
+ synchronized (this)
+ {
+ return super.getType();
+ }
+ }
+
+ @Override
+ public boolean isHidden() throws FileSystemException
+ {
+ synchronized (this)
+ {
+ return super.isHidden();
+ }
+ }
+
+ @Override
+ public boolean isReadable() throws FileSystemException
+ {
+ synchronized (this)
+ {
+ return super.isReadable();
+ }
+ }
+
+ @Override
+ public boolean isWriteable() throws FileSystemException
+ {
+ synchronized (this)
+ {
+ return super.isWriteable();
+ }
+ }
+
+ @Override
+ public boolean isExecutable() throws FileSystemException
+ {
+ synchronized (this)
+ {
+ return super.isExecutable();
+ }
+ }
+
+ @Override
+ public boolean setReadable(final boolean readable, final boolean ownerOnly) throws FileSystemException
+ {
+ synchronized (this)
+ {
+ return super.setReadable(readable, ownerOnly);
+ }
+ }
+
+ @Override
+ public boolean setWritable(final boolean writable, final boolean ownerOnly) throws FileSystemException
+ {
+ synchronized (this)
+ {
+ return super.setWritable(writable, ownerOnly);
+ }
+ }
+
+ @Override
+ public boolean setExecutable(final boolean executable, final boolean ownerOnly) throws FileSystemException
+ {
+ synchronized (this)
+ {
+ return super.setExecutable(executable, ownerOnly);
+ }
+ }
+
+ @Override
+ public void moveTo(final FileObject destFile) throws FileSystemException
+ {
+ synchronized (this)
+ {
+ super.moveTo(destFile);
+ }
+ }
+
+ @Override
+ public FileObject resolveFile(final String name, final NameScope scope) throws FileSystemException
+ {
+ synchronized (this)
+ {
+ return super.resolveFile(name, scope);
+ }
+ }
+
+ @Override
+ public FileObject resolveFile(final String path) throws FileSystemException
+ {
+ synchronized (this)
+ {
+ return super.resolveFile(path);
+ }
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/impl/URLStreamHandlerProxy.java b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/URLStreamHandlerProxy.java
new file mode 100644
index 0000000..ded84b4
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/URLStreamHandlerProxy.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.impl;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.net.URLStreamHandler;
+
+/**
+ * A proxy for URLs that are supported by the standard stream handler factory.
+ */
+class URLStreamHandlerProxy
+ extends URLStreamHandler
+{
+ @Override
+ protected URLConnection openConnection(final URL url)
+ throws IOException
+ {
+ final URL proxyURL = new URL(url.toExternalForm());
+ return proxyURL.openConnection();
+ }
+
+ @Override
+ protected void parseURL(final URL u,
+ final String spec,
+ final int start,
+ final int limit)
+ {
+ try
+ {
+ final URL url = new URL(u, spec);
+ setURL(u, url.getProtocol(), url.getHost(),
+ url.getPort(), url.getAuthority(), url.getUserInfo(),
+ url.getFile(), url.getQuery(), url.getRef());
+ }
+ catch (final MalformedURLException mue)
+ {
+ //We retrow this as a simple runtime exception.
+ //It is retrown in URL as a MalformedURLException anyway.
+ throw new RuntimeException(mue.getMessage());
+ }
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/impl/VFSClassLoader.java b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/VFSClassLoader.java
new file mode 100644
index 0000000..e5e07dc
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/VFSClassLoader.java
@@ -0,0 +1,419 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.impl;
+
+import java.io.IOException;
+import java.net.URL;
+import java.security.CodeSource;
+import java.security.Permission;
+import java.security.PermissionCollection;
+import java.security.Permissions;
+import java.security.SecureClassLoader;
+import java.security.cert.Certificate;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.List;
+import java.util.jar.Attributes;
+import java.util.jar.Attributes.Name;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.NameScope;
+
+
+/**
+ * A class loader that can load classes and resources from a search path.
+ * <p>
+ * The search path can consist of VFS FileObjects referring both to folders
+ * and JAR files. Any FileObject of type FileType.FILE is assumed to be a JAR and
+ * is opened by creating a layered file system with the "jar" scheme.
+ * <p>
+ * TODO - Test this with signed Jars and a SecurityManager.
+ *
+ * @see FileSystemManager#createFileSystem
+ */
+public class VFSClassLoader extends SecureClassLoader
+{
+ private final ArrayList<FileObject> resources = new ArrayList<FileObject>();
+
+ /**
+ * Constructors a new VFSClassLoader for the given file.
+ *
+ * @param file the file to load the classes and resources from.
+ * @param manager the FileManager to use when trying create a layered Jar file
+ * system.
+ * @throws FileSystemException if an error occurs.
+ */
+ public VFSClassLoader(final FileObject file,
+ final FileSystemManager manager)
+ throws FileSystemException
+ {
+ this(new FileObject[]{file}, manager, null);
+ }
+
+ /**
+ * Constructors a new VFSClassLoader for the given file.
+ *
+ * @param file the file to load the classes and resources from.
+ * @param manager the FileManager to use when trying create a layered Jar file
+ * system.
+ * @param parent the parent class loader for delegation.
+ * @throws FileSystemException if an error occurs.
+ */
+ public VFSClassLoader(final FileObject file,
+ final FileSystemManager manager,
+ final ClassLoader parent)
+ throws FileSystemException
+ {
+ this(new FileObject[]{file}, manager, parent);
+ }
+
+ /**
+ * Constructors a new VFSClassLoader for the given files. The files will
+ * be searched in the order specified.
+ *
+ * @param files the files to load the classes and resources from.
+ * @param manager the FileManager to use when trying create a layered Jar file
+ * system.
+ * @throws FileSystemException if an error occurs.
+ */
+ public VFSClassLoader(final FileObject[] files,
+ final FileSystemManager manager)
+ throws FileSystemException
+ {
+ this(files, manager, null);
+ }
+
+ /**
+ * Constructors a new VFSClassLoader for the given FileObjects.
+ * The FileObjects will be searched in the order specified.
+ *
+ * @param files the FileObjects to load the classes and resources from.
+ * @param manager the FileManager to use when trying create a layered Jar file
+ * system.
+ * @param parent the parent class loader for delegation.
+ * @throws FileSystemException if an error occurs.
+ */
+ public VFSClassLoader(final FileObject[] files,
+ final FileSystemManager manager,
+ final ClassLoader parent) throws FileSystemException
+ {
+ super(parent);
+ addFileObjects(manager, files);
+ }
+
+ /**
+ * Provide access to the file objects this class loader represents.
+ *
+ * @return An array of FileObjects.
+ * @since 2.0
+ */
+ public FileObject[] getFileObjects()
+ {
+ return resources.toArray(new FileObject[resources.size()]);
+ }
+
+ /**
+ * Appends the specified FileObjects to the list of FileObjects to search
+ * for classes and resources.
+ *
+ * @param manager The FileSystemManager.
+ * @param files the FileObjects to append to the search path.
+ * @throws FileSystemException if an error occurs.
+ */
+ private void addFileObjects(final FileSystemManager manager,
+ final FileObject[] files) throws FileSystemException
+ {
+ for (FileObject file : files)
+ {
+ if (!file.exists())
+ {
+ // Does not exist - skip
+ continue;
+ }
+
+ // TODO - use federation instead
+ if (manager.canCreateFileSystem(file))
+ {
+ // Use contents of the file
+ file = manager.createFileSystem(file);
+ }
+
+ resources.add(file);
+ }
+ }
+
+ /**
+ * Finds and loads the class with the specified name from the search
+ * path.
+ *
+ * @throws ClassNotFoundException if the class is not found.
+ */
+ @Override
+ protected Class<?> findClass(final String name) throws ClassNotFoundException
+ {
+ try
+ {
+ final String path = name.replace('.', '/').concat(".class");
+ final Resource res = loadResource(path);
+ if (res == null)
+ {
+ throw new ClassNotFoundException(name);
+ }
+ return defineClass(name, res);
+ }
+ catch (final IOException ioe)
+ {
+ throw new ClassNotFoundException(name, ioe);
+ }
+ }
+
+ /**
+ * Loads and verifies the class with name and located with res.
+ */
+ private Class<?> defineClass(final String name, final Resource res)
+ throws IOException
+ {
+ final URL url = res.getCodeSourceURL();
+ final String pkgName = res.getPackageName();
+ if (pkgName != null)
+ {
+ final Package pkg = getPackage(pkgName);
+ if (pkg != null)
+ {
+ if (pkg.isSealed())
+ {
+ if (!pkg.isSealed(url))
+ {
+ throw new FileSystemException("vfs.impl/pkg-sealed-other-url", pkgName);
+ }
+ }
+ else
+ {
+ if (isSealed(res))
+ {
+ throw new FileSystemException("vfs.impl/pkg-sealing-unsealed", pkgName);
+ }
+ }
+ }
+ else
+ {
+ definePackage(pkgName, res);
+ }
+ }
+
+ final byte[] bytes = res.getBytes();
+ final Certificate[] certs =
+ res.getFileObject().getContent().getCertificates();
+ final CodeSource cs = new CodeSource(url, certs);
+ return defineClass(name, bytes, 0, bytes.length, cs);
+ }
+
+ /**
+ * Returns true if the we should seal the package where res resides.
+ */
+ private boolean isSealed(final Resource res)
+ throws FileSystemException
+ {
+ final String sealed = res.getPackageAttribute(Attributes.Name.SEALED);
+ return "true".equalsIgnoreCase(sealed);
+ }
+
+ /**
+ * Reads attributes for the package and defines it.
+ */
+ private Package definePackage(final String name,
+ final Resource res)
+ throws FileSystemException
+ {
+ // TODO - check for MANIFEST_ATTRIBUTES capability first
+ final String specTitle = res.getPackageAttribute(Name.SPECIFICATION_TITLE);
+ final String specVendor = res.getPackageAttribute(Attributes.Name.SPECIFICATION_VENDOR);
+ final String specVersion = res.getPackageAttribute(Name.SPECIFICATION_VERSION);
+ final String implTitle = res.getPackageAttribute(Name.IMPLEMENTATION_TITLE);
+ final String implVendor = res.getPackageAttribute(Name.IMPLEMENTATION_VENDOR);
+ final String implVersion = res.getPackageAttribute(Name.IMPLEMENTATION_VERSION);
+
+ final URL sealBase;
+ if (isSealed(res))
+ {
+ sealBase = res.getCodeSourceURL();
+ }
+ else
+ {
+ sealBase = null;
+ }
+
+ return definePackage(name, specTitle, specVersion, specVendor,
+ implTitle, implVersion, implVendor, sealBase);
+ }
+
+ /**
+ * Calls super.getPermissions both for the code source and also
+ * adds the permissions granted to the parent layers.
+ * @param cs the CodeSource.
+ * @return The PermissionCollections.
+ */
+ @Override
+ protected PermissionCollection getPermissions(final CodeSource cs)
+ {
+ try
+ {
+ final String url = cs.getLocation().toString();
+ final FileObject file = lookupFileObject(url);
+ if (file == null)
+ {
+ return super.getPermissions(cs);
+ }
+
+ final FileObject parentLayer = file.getFileSystem().getParentLayer();
+ if (parentLayer == null)
+ {
+ return super.getPermissions(cs);
+ }
+
+ final Permissions combi = new Permissions();
+ PermissionCollection permCollect = super.getPermissions(cs);
+ copyPermissions(permCollect, combi);
+
+ for (FileObject parent = parentLayer;
+ parent != null;
+ parent = parent.getFileSystem().getParentLayer())
+ {
+ final CodeSource parentcs =
+ new CodeSource(parent.getURL(),
+ parent.getContent().getCertificates());
+ permCollect = super.getPermissions(parentcs);
+ copyPermissions(permCollect, combi);
+ }
+
+ return combi;
+ }
+ catch (final FileSystemException fse)
+ {
+ throw new SecurityException(fse.getMessage());
+ }
+ }
+
+ /**
+ * Copies the permissions from src to dest.
+ * @param src The source PermissionCollection.
+ * @param dest The destination PermissionCollection.
+ */
+ protected void copyPermissions(final PermissionCollection src,
+ final PermissionCollection dest)
+ {
+ for (final Enumeration<Permission> elem = src.elements(); elem.hasMoreElements();)
+ {
+ final Permission permission = elem.nextElement();
+ dest.add(permission);
+ }
+ }
+
+ /**
+ * Does a reverse lookup to find the FileObject when we only have the
+ * URL.
+ */
+ private FileObject lookupFileObject(final String name)
+ {
+ final Iterator<FileObject> it = resources.iterator();
+ while (it.hasNext())
+ {
+ final FileObject object = it.next();
+ if (name.equals(object.getName().getURI()))
+ {
+ return object;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Finds the resource with the specified name from the search path.
+ * This returns null if the resource is not found.
+ * @param name The resource name.
+ * @return The URL that matches the resource.
+ */
+ @Override
+ protected URL findResource(final String name)
+ {
+ try
+ {
+ final Resource res = loadResource(name);
+ if (res != null)
+ {
+ return res.getURL();
+ }
+ return null;
+ }
+ catch (final Exception ignored)
+ {
+ return null; // TODO: report?
+ }
+ }
+
+ /**
+ * Returns an Enumeration of all the resources in the search path
+ * with the specified name.
+ * <p>
+ * Gets called from {@link ClassLoader#getResources(String)} after
+ * parent class loader was questioned.
+ *
+ * @param name The resources to find.
+ * @return An Enumeration of the resources associated with the name.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ protected Enumeration<URL> findResources(final String name) throws IOException
+ {
+ final List<URL> result = new ArrayList<URL>(2);
+
+ for (FileObject baseFile : resources)
+ {
+ final FileObject file = baseFile.resolveFile(name, NameScope.DESCENDENT_OR_SELF);
+ if (file.exists())
+ {
+ result.add(new Resource(name, baseFile, file).getURL());
+ }
+ }
+
+ return Collections.enumeration(result);
+ }
+
+ /**
+ * Searches through the search path of for the first class or resource
+ * with specified name.
+ * @param name The resource to load.
+ * @return The Resource.
+ * @throws FileSystemException if an error occurs.
+ */
+ private Resource loadResource(final String name) throws FileSystemException
+ {
+ for (final FileObject baseFile : resources)
+ {
+ final FileObject file = baseFile.resolveFile(name, NameScope.DESCENDENT_OR_SELF);
+ if (file.exists())
+ {
+ return new Resource(name, baseFile, file);
+ }
+ }
+ return null;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/impl/VirtualFileName.java b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/VirtualFileName.java
new file mode 100644
index 0000000..c3defbf
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/VirtualFileName.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.impl;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+
+/**
+ * A simple Filename to hold the scheme for to be created virtual filesytsem.
+ */
+public class VirtualFileName extends AbstractFileName
+{
+ public VirtualFileName(final String scheme, final String absPath, final FileType type)
+ {
+ super(scheme, absPath, type);
+ }
+
+ @Override
+ public FileName createName(final String absPath, final FileType type)
+ {
+ return new VirtualFileName(getScheme(), absPath, type);
+ }
+
+ @Override
+ protected void appendRootUri(final StringBuilder buffer, final boolean addPassword)
+ {
+ buffer.append(getScheme());
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/impl/VirtualFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/VirtualFileProvider.java
new file mode 100644
index 0000000..3556b63
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/VirtualFileProvider.java
@@ -0,0 +1,82 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.impl;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileSystem;
+import org.apache.commons.vfs2.provider.AbstractVfsContainer;
+
+
+/**
+ * A virtual filesystem provider.
+ */
+public class VirtualFileProvider extends AbstractVfsContainer
+{
+ /**
+ * Creates a virtual file system, with the supplied file as its root.
+ *
+ * @param rootFile The root of the file system.
+ * @return A FileObject in the FileSystem.
+ * @throws FileSystemException if an error occurs.
+ */
+ public FileObject createFileSystem(final FileObject rootFile) throws FileSystemException
+ {
+ final AbstractFileName rootName = (AbstractFileName)
+ getContext().getFileSystemManager().resolveName(rootFile.getName(), FileName.ROOT_PATH);
+ final VirtualFileSystem fs = new VirtualFileSystem(rootName, rootFile.getFileSystem().getFileSystemOptions());
+ addComponent(fs);
+ fs.addJunction(FileName.ROOT_PATH, rootFile);
+ return fs.getRoot();
+ }
+
+ /**
+ * Creates an empty virtual file system.
+ *
+ * @param rootUri The root of the file system.
+ * @return A FileObject in the FileSystem.
+ * @throws FileSystemException if an error occurs.
+ */
+ public FileObject createFileSystem(final String rootUri) throws FileSystemException
+ {
+ final AbstractFileName rootName =
+ new VirtualFileName(rootUri, FileName.ROOT_PATH, FileType.FOLDER);
+ final VirtualFileSystem fs = new VirtualFileSystem(rootName, null);
+ addComponent(fs);
+ return fs.getRoot();
+ }
+
+ /**
+ * Close a VirtualFileSystem by removing it from the
+ * {@code #components} list of this provider.
+ * <p>
+ * This gets called from DefaultFileManager#_closeFileSystem.
+ *
+ * @param filesystem the file system remembered by this provider.
+ */
+ void closeFileSystem(final FileSystem filesystem)
+ {
+ final AbstractFileSystem fs = (AbstractFileSystem) filesystem;
+
+ removeComponent(fs);
+ fs.close();
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/impl/VirtualFileSystem.java b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/VirtualFileSystem.java
new file mode 100644
index 0000000..22cc39a
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/VirtualFileSystem.java
@@ -0,0 +1,206 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.impl;
+
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.NameScope;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileSystem;
+import org.apache.commons.vfs2.provider.DelegateFileObject;
+
+/**
+ * A logical file system, made up of set of junctions, or links, to files from
+ * other file systems.
+ * <p>
+ * TODO - Handle nested junctions.
+ */
+public class VirtualFileSystem extends AbstractFileSystem
+{
+ private final Map<FileName, FileObject> junctions = new HashMap<FileName, FileObject>();
+
+ public VirtualFileSystem(final AbstractFileName rootName, final FileSystemOptions fileSystemOptions)
+ {
+ super(rootName, null, fileSystemOptions);
+ }
+
+ /**
+ * Adds the capabilities of this file system.
+ */
+ @Override
+ protected void addCapabilities(final Collection<Capability> caps)
+ {
+ // TODO - this isn't really true
+ caps.add(Capability.ATTRIBUTES);
+ caps.add(Capability.CREATE);
+ caps.add(Capability.DELETE);
+ caps.add(Capability.GET_TYPE);
+ caps.add(Capability.JUNCTIONS);
+ caps.add(Capability.GET_LAST_MODIFIED);
+ caps.add(Capability.SET_LAST_MODIFIED_FILE);
+ caps.add(Capability.SET_LAST_MODIFIED_FOLDER);
+ caps.add(Capability.LIST_CHILDREN);
+ caps.add(Capability.READ_CONTENT);
+ caps.add(Capability.SIGNING);
+ caps.add(Capability.WRITE_CONTENT);
+ caps.add(Capability.APPEND_CONTENT);
+ }
+
+ /**
+ * Creates a file object. This method is called only if the requested
+ * file is not cached.
+ */
+ @Override
+ protected FileObject createFile(final AbstractFileName name) throws Exception
+ {
+ // Find the file that the name points to
+ final FileName junctionPoint = getJunctionForFile(name);
+ final FileObject file;
+ if (junctionPoint != null)
+ {
+ // Resolve the real file
+ final FileObject junctionFile = junctions.get(junctionPoint);
+ final String relName = junctionPoint.getRelativeName(name);
+ file = junctionFile.resolveFile(relName, NameScope.DESCENDENT_OR_SELF);
+ }
+ else
+ {
+ file = null;
+ }
+
+ // Return a wrapper around the file
+ return new DelegateFileObject(name, this, file);
+ }
+
+ /**
+ * Adds a junction to this file system.
+ * @param junctionPoint The location of the junction.
+ * @param targetFile The target file to base the junction on.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public void addJunction(final String junctionPoint,
+ final FileObject targetFile)
+ throws FileSystemException
+ {
+ final FileName junctionName = getFileSystemManager().resolveName(getRootName(), junctionPoint);
+
+ // Check for nested junction - these are not supported yet
+ if (getJunctionForFile(junctionName) != null)
+ {
+ throw new FileSystemException("vfs.impl/nested-junction.error", junctionName);
+ }
+
+ try
+ {
+ // Add to junction table
+ junctions.put(junctionName, targetFile);
+
+ // Attach to file
+ final DelegateFileObject junctionFile = (DelegateFileObject) getFileFromCache(junctionName);
+ if (junctionFile != null)
+ {
+ junctionFile.setFile(targetFile);
+ }
+
+ // Create ancestors of junction point
+ FileName childName = junctionName;
+ boolean done = false;
+ for (AbstractFileName parentName = (AbstractFileName) childName.getParent();
+ !done && parentName != null;
+ childName = parentName, parentName = (AbstractFileName) parentName.getParent())
+ {
+ DelegateFileObject file = (DelegateFileObject) getFileFromCache(parentName);
+ if (file == null)
+ {
+ file = new DelegateFileObject(parentName, this, null);
+ putFileToCache(file);
+ }
+ else
+ {
+ done = file.exists();
+ }
+
+ // As this is the parent of our junction it has to be a folder
+ file.attachChild(childName, FileType.FOLDER);
+ }
+
+ // TODO - attach all cached children of the junction point to their real file
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("vfs.impl/create-junction.error", junctionName, e);
+ }
+ }
+
+ /**
+ * Removes a junction from this file system.
+ * @param junctionPoint The junction to remove.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public void removeJunction(final String junctionPoint)
+ throws FileSystemException
+ {
+ final FileName junctionName = getFileSystemManager().resolveName(getRootName(), junctionPoint);
+ junctions.remove(junctionName);
+
+ // TODO - remove from parents of junction point
+ // TODO - detach all cached children of the junction point from their real file
+ }
+
+ /**
+ * Locates the junction point for the junction containing the given file.
+ * @param name The FileName.
+ * @return the FileName where the junction occurs.
+ */
+ private FileName getJunctionForFile(final FileName name)
+ {
+ if (junctions.containsKey(name))
+ {
+ // The name points to the junction point directly
+ return name;
+ }
+
+ // Find matching junction
+ for (final FileName junctionPoint : junctions.keySet())
+ {
+ if (junctionPoint.isDescendent(name))
+ {
+ return junctionPoint;
+ }
+ }
+
+ // None
+ return null;
+ }
+
+ @Override
+ public void close()
+ {
+ super.close();
+ junctions.clear();
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/impl/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/package.html
new file mode 100644
index 0000000..5fd7b1a
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>The standard VFS implementation.</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/impl/providers.xml b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/providers.xml
new file mode 100644
index 0000000..f8d571c
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/impl/providers.xml
@@ -0,0 +1,144 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<providers>
+ <default-provider class-name="org.apache.commons.vfs2.provider.url.UrlFileProvider">
+ </default-provider>
+ <provider class-name="org.apache.commons.vfs2.provider.local.DefaultLocalFileProvider">
+ <scheme name="file"/>
+ </provider>
+ <provider class-name="org.apache.commons.vfs2.provider.zip.ZipFileProvider">
+ <scheme name="zip"/>
+ </provider>
+ <provider class-name="org.apache.commons.vfs2.provider.tar.TarFileProvider">
+ <scheme name="tar"/>
+ <if-available class-name="org.apache.commons.compress.archivers.tar.TarArchiveOutputStream"/>
+ </provider>
+
+ <provider class-name="org.apache.commons.vfs2.provider.bzip2.Bzip2FileProvider">
+ <scheme name="bz2"/>
+ <if-available class-name="org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream"/>
+ </provider>
+ <provider class-name="org.apache.commons.vfs2.provider.gzip.GzipFileProvider">
+ <scheme name="gz"/>
+ </provider>
+
+ <provider class-name="org.apache.commons.vfs2.provider.jar.JarFileProvider">
+ <scheme name="jar"/>
+ <scheme name="sar"/>
+ <scheme name="ear"/>
+ <scheme name="par"/>
+ <scheme name="ejb3"/>
+ <scheme name="war"/>
+ </provider>
+ <provider class-name="org.apache.commons.vfs2.provider.temp.TemporaryFileProvider">
+ <scheme name="tmp"/>
+ </provider>
+ <provider class-name="org.apache.commons.vfs2.provider.ftp.FtpFileProvider">
+ <scheme name="ftp"/>
+ <if-available class-name="org.apache.commons.net.ftp.FTPFile"/>
+ </provider>
+ <provider class-name="org.apache.commons.vfs2.provider.ftps.FtpsFileProvider">
+ <scheme name="ftps"/>
+ <if-available class-name="org.apache.commons.net.ftp.FTPFile"/>
+ </provider>
+ <provider class-name="org.apache.commons.vfs2.provider.http.HttpFileProvider">
+ <scheme name="http"/>
+ <if-available class-name="org.apache.commons.httpclient.HttpClient"/>
+ </provider>
+ <provider class-name="org.apache.commons.vfs2.provider.https.HttpsFileProvider">
+ <scheme name="https"/>
+ <if-available class-name="org.apache.commons.httpclient.HttpClient"/>
+ </provider>
+ <provider class-name="org.apache.commons.vfs2.provider.sftp.SftpFileProvider">
+ <scheme name="sftp"/>
+ <if-available class-name="javax.crypto.Cipher"/>
+ <if-available class-name="com.jcraft.jsch.JSch"/>
+ </provider>
+ <provider class-name="org.apache.commons.vfs2.provider.res.ResourceFileProvider">
+ <scheme name="res"/>
+ </provider>
+ <provider class-name="org.apache.commons.vfs2.provider.webdav.WebdavFileProvider">
+ <scheme name="webdav"/>
+ <if-available class-name="org.apache.commons.httpclient.HttpClient"/>
+ <if-available class-name="org.apache.jackrabbit.webdav.client.methods.DavMethod"/>
+ </provider>
+ <!--
+ <provider class-name="org.apache.commons.vfs2.provider.svn.SvnFileProvider">
+ <scheme name="svnhttps"/>
+ </provider>
+ -->
+ <!--
+ <provider class-name="org.apache.commons.vfs2.provider.tar.TgzFileProvider">
+ <scheme name="tgz"/>
+ <if-available scheme="gz"/>
+ <if-available scheme="tar"/>
+ </provider>
+ <provider class-name="org.apache.commons.vfs2.provider.tar.Tbz2FileProvider">
+ <scheme name="tbz2"/>
+ <if-available scheme="bz2"/>
+ <if-available scheme="tar"/>
+ </provider>
+ -->
+ <provider class-name="org.apache.commons.vfs2.provider.tar.TarFileProvider">
+ <scheme name="tgz"/>
+ <if-available scheme="gz"/>
+ <if-available scheme="tar"/>
+ </provider>
+ <provider class-name="org.apache.commons.vfs2.provider.tar.TarFileProvider">
+ <scheme name="tbz2"/>
+ <if-available scheme="bz2"/>
+ <if-available scheme="tar"/>
+ </provider>
+ <provider class-name="org.apache.commons.vfs2.provider.ram.RamFileProvider">
+ <scheme name="ram"/>
+ </provider>
+ <provider class-name="org.apache.commons.vfs2.provider.hdfs.HdfsFileProvider">
+ <scheme name="hdfs"/>
+ <if-available class-name="org.apache.hadoop.fs.FileSystem"/>
+ </provider>
+
+ <extension-map extension="zip" scheme="zip"/>
+ <extension-map extension="tar" scheme="tar"/>
+ <mime-type-map mime-type="application/zip" scheme="zip"/>
+ <mime-type-map mime-type="application/x-tar" scheme="tar"/>
+ <mime-type-map mime-type="application/x-gzip" scheme="gz"/>
+ <!--
+ <mime-type-map mime-type="application/x-tgz" scheme="tgz"/>
+ -->
+ <extension-map extension="jar" scheme="jar"/>
+ <extension-map extension="bz2" scheme="bz2"/>
+ <extension-map extension="gz" scheme="gz"/>
+ <!--
+ <extension-map extension="tgz" scheme="tgz"/>
+ <extension-map extension="tbz2" scheme="tbz2"/>
+ -->
+ <extension-map extension="tgz" scheme="tar"/>
+ <extension-map extension="tbz2" scheme="tar"/>
+
+ <!--
+ <filter-map class-name="org.apache.commons.vfs2.content.bzip2.Bzip2Compress">
+ <extension name="bz2"/>
+ <extension name="tbz2"/>
+ <if-available class-name="org.apache.commons.compress.bzip2.CBZip2InputStream"/>
+ </filter-map>
+ <filter-map class-name="org.apache.commons.vfs2.content.gzip.GzipCompress">
+ <extension name="gz"/>
+ <extension name="tgz"/>
+ <mime-type name="application/x-tgz" />
+ </filter-map>
+ -->
+</providers>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/operations/AbstractFileOperation.java b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/AbstractFileOperation.java
new file mode 100644
index 0000000..41c3c04
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/AbstractFileOperation.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.operations;
+
+import org.apache.commons.vfs2.FileObject;
+
+/**
+ *
+ * @since 0.1
+ */
+public abstract class AbstractFileOperation implements FileOperation
+{
+ /**
+ * FileObject which the FileOperation is operate on.
+ */
+ private final FileObject fileObject;
+
+ /**
+ * @param file The FileObject.
+ */
+ public AbstractFileOperation(final FileObject file)
+ {
+ fileObject = file;
+ }
+
+ /**
+ * @return an instance of FileObject which this FileOperation is operate on.
+ */
+ protected FileObject getFileObject()
+ {
+ return fileObject;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/operations/AbstractFileOperationProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/AbstractFileOperationProvider.java
new file mode 100644
index 0000000..5707fa4
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/AbstractFileOperationProvider.java
@@ -0,0 +1,167 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.operations;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Iterator;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+
+
+/**
+ *
+ * @since 0.1
+ */
+public abstract class AbstractFileOperationProvider implements FileOperationProvider
+{
+
+ /**
+ * Available operations. Operations could be registered for different schemes.
+ * Some operations can work only for "file" scheme, other - for "svnhttp(s)",
+ * "svn", "svnssh", but not for "file", etc. The Map has scheme as a key and
+ * Collection of operations that are available for that scheme.
+ */
+ private final Collection<Class<? extends FileOperation>> operations =
+ new ArrayList<Class<? extends FileOperation>>();
+
+ /**
+ * Gather available operations for the specified FileObject and put them into
+ * specified operationsList.
+ *
+ * @param operationsList
+ * the list of available operations for the specified FileObject.
+ * The operationList contains classes of available operations, e.g.
+ * Class objects.
+ * @param file
+ * the FileObject for which we want to get the list of available
+ * operations.
+ * @throws FileSystemException if list of operations cannot be retrieved.
+ */
+ @Override
+ public final void collectOperations(final Collection<Class<? extends FileOperation>> operationsList,
+ final FileObject file) throws FileSystemException
+ {
+ doCollectOperations(operations, operationsList, file);
+ }
+
+ /**
+ * Gather available operations for the specified FileObject and put them into
+ * specified operationsList.
+ *
+ * @param availableOperations
+ * the list of available operations for the specified FileObject.
+ * @param resultList
+ * List to be filled with applicable operations.
+ * @param file
+ * the FileObject for which we want to get the list of available
+ * operations.
+ * @throws FileSystemException if list of operations cannot be retrieved.
+ * @see #collectOperations(Collection operationsList, FileObject file)
+ */
+ protected abstract void doCollectOperations(
+ final Collection<Class<? extends FileOperation>> availableOperations,
+ final Collection<Class<? extends FileOperation>> resultList,
+ final FileObject file) throws FileSystemException;
+
+ /**
+ * @param file
+ * the FileObject for which we need a operation.
+ * @param operationClass
+ * the Class which instance we are needed.
+ * @return the required operation instance.
+ * @throws FileSystemException if operation cannot be retrieved.
+ */
+ @Override
+ public final FileOperation getOperation(final FileObject file, final Class<? extends FileOperation> operationClass)
+ throws FileSystemException
+ {
+ final Class<? extends FileOperation> implementation = lookupOperation(operationClass);
+
+ final FileOperation operationInstance = instantiateOperation(file, implementation);
+
+ return operationInstance;
+ }
+
+ /**
+ * Get operation instance for specified FileOperation subclass.
+ *
+ * @param file the file this operation should act on.
+ * @param operationClass the class of an file operation interface to instantiate.
+ * @return a new file operation
+ * @throws FileSystemException if operation cannot be instantiated.
+ */
+ protected abstract FileOperation instantiateOperation(final FileObject file,
+ final Class<? extends FileOperation> operationClass) throws FileSystemException;
+
+ /**
+ * Find class implementing a specific operation interface.
+ *
+ * @param operationClass the interface which is requested.
+ * @return never returns null
+ * @throws FileSystemException if operationClass is not a known FileOperation interface.
+ */
+ protected final Class<? extends FileOperation> lookupOperation(final Class<? extends FileOperation> operationClass)
+ throws FileSystemException
+ {
+ // check validity of passed class
+ if (!FileOperation.class.isAssignableFrom(operationClass))
+ {
+ throw new FileSystemException("vfs.operation/wrong-type.error", operationClass);
+ }
+
+ // find appropriate class
+ Class<? extends FileOperation> foundClass = null;
+ final Iterator<Class<? extends FileOperation>> iterator = operations.iterator();
+ while (iterator.hasNext())
+ {
+ final Class<? extends FileOperation> operation = iterator.next();
+ if (operationClass.isAssignableFrom(operation))
+ {
+ foundClass = operation;
+ break;
+ }
+ }
+
+ if (foundClass == null)
+ {
+ throw new FileSystemException("vfs.operation/not-found.error", operationClass);
+ }
+
+ return foundClass;
+ }
+
+ /**
+ * Add new FileOperation to list of known operations.
+ *
+ * @param operationClass a class implementing FileOperation.
+ * @throws FileSystemException if instances of the class cannot be assigned to FileOperation.
+ */
+ protected final void addOperation(final Class<? extends FileOperation> operationClass)
+ throws FileSystemException
+ {
+ // check validity of passed class
+ if (!FileOperation.class.isAssignableFrom(operationClass))
+ {
+ throw new FileSystemException("vfs.operation/cant-register.error", operationClass);
+ }
+
+ // ok, lets add it to the list
+ operations.add(operationClass);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/operations/DefaultFileOperations.java b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/DefaultFileOperations.java
new file mode 100644
index 0000000..c92c1c8
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/DefaultFileOperations.java
@@ -0,0 +1,148 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.operations;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemManager;
+
+/**
+ *
+ * @since 0.1
+ */
+public class DefaultFileOperations implements FileOperations
+{
+ /**
+ */
+ private final FileSystemManager fsmanager;
+
+ /**
+ */
+ private final FileObject fileObject;
+
+ /**
+ *
+ * @param file The file.
+ */
+ public DefaultFileOperations(final FileObject file)
+ {
+ fileObject = file;
+
+ fsmanager = file.getFileSystem().getFileSystemManager();
+ }
+
+ /**
+ * @return The operation classes.
+ * @throws FileSystemException If an error occurs.
+ */
+ @Override
+ public Class<? extends FileOperation>[] getOperations() throws FileSystemException
+ {
+
+ final String scheme = fileObject.getURL().getProtocol();
+ final FileOperationProvider[] providers = fsmanager
+ .getOperationProviders(scheme);
+
+ if (providers == null)
+ {
+ return null;
+ }
+
+ final List<Class<? extends FileOperation>> operations = new ArrayList<Class<? extends FileOperation>>();
+
+ for (final FileOperationProvider provider : providers)
+ {
+ provider.collectOperations(operations, fileObject);
+ }
+
+ @SuppressWarnings("unchecked")
+ final
+ Class<? extends FileOperation>[] array =
+ (Class<? extends FileOperation>[]) operations.toArray(new Class<?>[] {});
+ return array;
+ }
+
+ /**
+ * @param operationClass The Class that performs the operation.
+ * @return The FileOperation.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileOperation getOperation(final Class<? extends FileOperation> operationClass)
+ throws FileSystemException
+ {
+
+ final String scheme = fileObject.getURL().getProtocol();
+ final FileOperationProvider[] providers = fsmanager
+ .getOperationProviders(scheme);
+
+ if (providers == null)
+ {
+ throw new FileSystemException(
+ "vfs.operation/operation-not-supported.error", operationClass);
+ }
+
+ FileOperation resultOperation = null;
+
+ for (final FileOperationProvider provider : providers)
+ {
+ resultOperation = provider.getOperation(fileObject, operationClass);
+
+ if (resultOperation != null)
+ {
+ break;
+ }
+ }
+
+ if (resultOperation == null)
+ {
+ throw new FileSystemException(
+ "vfs.operation/operation-not-supported.error", operationClass);
+ }
+
+ return resultOperation;
+ }
+
+ /**
+ * @param operationClass the operation's class.
+ * @return true if the operation of specified class is supported for current
+ * FileObject and false otherwise.
+ *
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public boolean hasOperation(final Class<? extends FileOperation> operationClass) throws FileSystemException
+ {
+ final Class<? extends FileOperation>[] operations = getOperations();
+ if (operations == null)
+ {
+ return false;
+ }
+
+ for (final Class<? extends FileOperation> operation : operations)
+ {
+ if (operationClass.isAssignableFrom(operation))
+ {
+ return true;
+ }
+ }
+ return false;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/operations/FileOperation.java b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/FileOperation.java
new file mode 100644
index 0000000..2d4d883
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/FileOperation.java
@@ -0,0 +1,55 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.operations;
+
+import org.apache.commons.vfs2.FileSystemException;
+
+/**
+ * <p>
+ * A FileOperation is an object that brings an extra function to a FileObject.
+ * The VFS provides the basic functionality to deal with FileObject's. That is
+ * create, delete, rename, copy, and so on functions. However, if you are working with
+ * FileSystem and its files are, for example, under Version Control System (VCS)
+ * you might want to get an access to the versioning framework and to be able to
+ * manage your files regarding VCS (e.g. commit them, update, get logs, etc.).
+ * Such type of extended functionality is provided by FileOperation.
+ * </p>
+ * <p>
+ * The FileOperation interface is a genetic interface that should not be
+ * implemented directly. It rather should be extended by other interfaces that
+ * provide some concrete functions.
+ * </p>
+ * <p>
+ * FileOperation is provided by
+ *
+ * @see FileOperationProvider Especially the FileOperationProvider is responsible
+ * for looking up and instantiating any concrete FileOperation.
+ * </p>
+ *
+ * @since 0.1
+ */
+public interface FileOperation
+{
+
+ /**
+ * Performs necessary actions that are related to the concrete
+ * implementation of a FileOperation.
+ *
+ * @throws FileSystemException if an error occurs
+ */
+ void process() throws FileSystemException;
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/operations/FileOperationProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/FileOperationProvider.java
new file mode 100644
index 0000000..70e1b97
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/FileOperationProvider.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.operations;
+
+import java.util.Collection;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+
+/**
+ * FileOperationProvider is responsible for dealing with FileOperation's.
+ *
+ * @since 0.1
+ */
+public interface FileOperationProvider
+{
+
+ /**
+ * Gather available operations for the specified FileObject and put them into
+ * specified operationsList.
+ *
+ * @param operationsList
+ * the list of available operations for the specified FileObject.
+ * The operationList contains classes of available operations, e.g.
+ * Class objects.
+ * @param file
+ * the FileObject for which we want to get the list of available
+ * operations.
+ *
+ * @throws FileSystemException
+ * if list of operations cannot be retrieved.
+ */
+ void collectOperations(final Collection<Class<? extends FileOperation>> operationsList, final FileObject file)
+ throws FileSystemException;
+
+ /**
+ * Get implementation for a given FileObject and FileOperation interface.
+ *
+ * @param file
+ * the FileObject for which we need a operation.
+ * @param operationClass
+ * the Class which instance we are needed.
+ * @return the required operation instance.
+ *
+ * @throws FileSystemException
+ * if operation cannot be retrieved.
+ */
+ FileOperation getOperation(final FileObject file, final Class<? extends FileOperation> operationClass)
+ throws FileSystemException;
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/operations/FileOperations.java b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/FileOperations.java
new file mode 100644
index 0000000..b0360cc
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/FileOperations.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.operations;
+
+import org.apache.commons.vfs2.FileSystemException;
+
+/**
+ * FileOperations interface provides API to work with operations.
+ *
+ * @see FileOperation on what a operation in the context of VFS is.
+ *
+ * @since 0.1
+ */
+public interface FileOperations
+{
+ /**
+ * @return all operations associated with the fileObject
+ * @throws FileSystemException if an error occurs.
+ */
+ Class<? extends FileOperation>[] getOperations() throws FileSystemException;
+
+ /**
+ * @param operationClass the operation Class.
+ * @return a operation implementing the given {@code operationClass}
+ * @throws FileSystemException if an error occus.
+ */
+ FileOperation getOperation(Class<? extends FileOperation> operationClass) throws FileSystemException;
+
+ /**
+ * @param operationClass the operation Class.
+ * @return if a operation {@code operationClass} is available
+ * @throws FileSystemException if an error ocurs.
+ */
+ boolean hasOperation(Class<? extends FileOperation> operationClass) throws FileSystemException;
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/operations/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/package.html
new file mode 100644
index 0000000..242e71c
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>VFS Operations handling.</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsAdd.java b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsAdd.java
new file mode 100644
index 0000000..0d67b79
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsAdd.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.operations.vcs;
+
+import org.apache.commons.vfs2.operations.FileOperation;
+
+/**
+ *
+ * @since 0.1
+ */
+public interface VcsAdd extends FileOperation
+{
+ /**
+ *
+ * @param makedir true if directories should be created, false otherwise.
+ */
+ void setMakedir(final boolean makedir);
+
+ /**
+ *
+ * @param recursive true if subdirectories should be processed.
+ */
+ void setRecursive(final boolean recursive);
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsCheckout.java b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsCheckout.java
new file mode 100644
index 0000000..2936514
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsCheckout.java
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.operations.vcs;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.operations.FileOperation;
+
+/**
+ *
+ * @since 0.1
+ */
+public interface VcsCheckout extends FileOperation
+{
+ /**
+ *
+ * @param revision The revision number.
+ */
+ void setRevision(final long revision);
+
+ /**
+ *
+ * @param recursive true if directories should be traversed.
+ */
+ void setRecursive(final boolean recursive);
+
+ /**
+ *
+ * @param targetDir directory under which retrieved files should be placed.
+ */
+ void setTargetDirectory(final FileObject targetDir);
+
+ /**
+ * @param export
+ * if true, administrative .svn directoies will not be created on
+ * the retrieved tree. The checkout operation in this case is
+ * equivalent to export function.
+ */
+ void setExport(final boolean export);
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsCommit.java b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsCommit.java
new file mode 100644
index 0000000..c470f80
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsCommit.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.operations.vcs;
+
+import org.apache.commons.vfs2.operations.FileOperation;
+
+/**
+ *
+ * @since 0.1
+ */
+public interface VcsCommit extends FileOperation
+{
+
+ /**
+ *
+ * @param isRecursive true if directories should be traversed.
+ */
+ void setRecursive(final boolean isRecursive);
+
+ /**
+ *
+ * @param message The message.
+ */
+ void setMessage(final String message);
+
+ /**
+ *
+ * @param listener Listener that is given control when a commit occurs.
+ */
+ void addCommitListener(final VcsCommitListener listener);
+
+ /**
+ *
+ * @param listener The Listener.
+ */
+ void removeCommitListener(final VcsCommitListener listener);
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsCommitListener.java b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsCommitListener.java
new file mode 100644
index 0000000..6fca045
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsCommitListener.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.operations.vcs;
+
+/**
+ *
+ * @since 0.1
+ */
+public interface VcsCommitListener
+{
+ /**
+ *
+ * @param path The path.
+ * @param contentStatus The status;
+ */
+ void commited(final String path, final VcsStatus contentStatus);
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsDelete.java b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsDelete.java
new file mode 100644
index 0000000..a3682bb
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsDelete.java
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.operations.vcs;
+
+import org.apache.commons.vfs2.operations.FileOperation;
+
+/**
+ *
+ * @since 0.1
+ */
+public interface VcsDelete extends FileOperation
+{
+ /**
+ *
+ * @param force true if the delete should be unconditional.
+ */
+ void setForce(final boolean force);
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsLog.java b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsLog.java
new file mode 100644
index 0000000..f8d1be3
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsLog.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.operations.vcs;
+
+import org.apache.commons.vfs2.operations.FileOperation;
+
+/**
+ *
+ * @since 0.1
+ */
+public interface VcsLog extends FileOperation
+{
+ /**
+ *
+ * @param startRev The start revision.
+ */
+ void setStartRevision(final long startRev);
+
+ /**
+ *
+ * @param endRev The end revision.
+ */
+ void setEndRevision(final long endRev);
+
+ /**
+ *
+ * @param handler The LogEntry handler.
+ */
+ void setLogEntryHandler(final VcsLogEntryHandler handler);
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsLogEntry.java b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsLogEntry.java
new file mode 100644
index 0000000..60dcea7
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsLogEntry.java
@@ -0,0 +1,113 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.operations.vcs;
+
+import java.util.Calendar;
+
+/**
+ *
+ * @since 0.1
+ */
+public class VcsLogEntry
+{
+ /**
+ */
+ private final String author;
+
+ /**
+ * Revision.
+ */
+ private final long revision;
+
+ /**
+ * Message.
+ */
+ private final String message;
+
+ /**
+ * Date.
+ */
+ private final Calendar date;
+
+ /**
+ * Path.
+ */
+ private final String path;
+
+ /**
+ *
+ * @param author The author.
+ * @param revision The revision.
+ * @param message The message.
+ * @param date The date.
+ * @param path The path.
+ */
+ public VcsLogEntry(final String author, final long revision,
+ final String message, final Calendar date, final String path)
+ {
+ this.author = author;
+ this.revision = revision;
+ this.message = message;
+ this.date = date;
+ this.path = path;
+ }
+
+ /**
+ *
+ * @return The author.
+ */
+ public String getAuthor()
+ {
+ return author;
+ }
+
+ /**
+ *
+ * @return The revision.
+ */
+ public long getRevision()
+ {
+ return revision;
+ }
+
+ /**
+ *
+ * @return The message.
+ */
+ public String getMessage()
+ {
+ return message;
+ }
+
+ /**
+ *
+ * @return The date.
+ */
+ public Calendar getDate()
+ {
+ return date;
+ }
+
+ /**
+ *
+ * @return The path.
+ */
+ public String getPath()
+ {
+ return path;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsLogEntryHandler.java b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsLogEntryHandler.java
new file mode 100644
index 0000000..74d8364
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsLogEntryHandler.java
@@ -0,0 +1,33 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.operations.vcs;
+
+import org.apache.commons.vfs2.FileSystemException;
+
+/**
+ *
+ * @since 0.1
+ */
+public interface VcsLogEntryHandler
+{
+ /**
+ *
+ * @param entry The log entry.
+ * @throws FileSystemException if an error occurs.
+ */
+ void handleLogEntry(final VcsLogEntry entry) throws FileSystemException;
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsModifyListener.java b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsModifyListener.java
new file mode 100644
index 0000000..1b800a2
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsModifyListener.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.operations.vcs;
+
+/**
+ *
+ * @since 0.1
+ */
+public interface VcsModifyListener
+{
+ /**
+ *
+ * @param path The path String.
+ * @param contentStatus The content status.
+ */
+ void modified(final String path, final VcsStatus contentStatus);
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsRevert.java b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsRevert.java
new file mode 100644
index 0000000..efe8229
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsRevert.java
@@ -0,0 +1,49 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.operations.vcs;
+
+import org.apache.commons.vfs2.operations.FileOperation;
+
+/**
+ * <p>
+ * Restores pristine working copy file and cancels all local modifications. In
+ * other words, VcsRevert replaces working copy file with the latest version
+ * from the repository.
+ * </p>
+ *
+ * @since 0.1
+ */
+public interface VcsRevert extends FileOperation
+{
+ /**
+ *
+ * @param recursive true if children should be processed.
+ */
+ void setRecursive(final boolean recursive);
+
+ /**
+ *
+ * @param listener The Listener to add.
+ */
+ void addModifyListener(final VcsModifyListener listener);
+
+ /**
+ *
+ * @param listener The Listener to remove.
+ */
+ void removeModifyListener(final VcsModifyListener listener);
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsStatus.java b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsStatus.java
new file mode 100644
index 0000000..f4e1f22
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsStatus.java
@@ -0,0 +1,63 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.operations.vcs;
+
+/**
+ *
+ * @since 0.1
+ */
+public enum VcsStatus
+{
+ UNKNOWN(-1),
+ NOT_MODIFIED(0),
+ ADDED(1),
+ CONFLICTED(2),
+ DELETED(3),
+ MERGED(4),
+ IGNORED(5),
+ MODIFIED(6),
+ REPLACED(7),
+ UNVERSIONED(8),
+ MISSING(9),
+ OBSTRUCTED(10),
+ REVERTED(11),
+ RESOLVED(12),
+ COPIED(13),
+ MOVED(14),
+ RESTORED(15),
+ UPDATED(16),
+ EXTERNAL(18),
+ CORRUPTED(19),
+ NOT_REVERTED(20);
+
+ private int status;
+
+
+ private VcsStatus(final int status)
+ {
+ this.status = status;
+ }
+
+ /**
+ *
+ * @return the status of FileObject
+ */
+ public int getStatus()
+ {
+ return status;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsUpdate.java b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsUpdate.java
new file mode 100644
index 0000000..3508ab6
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsUpdate.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.operations.vcs;
+
+import org.apache.commons.vfs2.operations.FileOperation;
+
+/**
+ *
+ * @since 0.1
+ */
+public interface VcsUpdate extends FileOperation
+{
+ /**
+ *
+ * @param revision The revision number.
+ */
+ void setRevision(final long revision);
+
+ /**
+ *
+ * @param isRecursive true if recursive.
+ */
+ void setRecursive(final boolean isRecursive);
+
+ /**
+ *
+ * @param listener The UpdateListener.
+ */
+ void addUpdateListener(final VcsUpdateListener listener);
+
+ /**
+ *
+ * @param listener The UpdateListener.
+ */
+ void removeUpdateListener(final VcsUpdateListener listener);
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsUpdateListener.java b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsUpdateListener.java
new file mode 100644
index 0000000..32eaa66
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsUpdateListener.java
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.operations.vcs;
+
+/**
+ *
+ * @since 0.1
+ */
+public interface VcsUpdateListener
+{
+ /**
+ *
+ * @param path The path.
+ * @param revision The revision number.
+ * @param contentStatus The status.
+ */
+ void updated(final String path, final long revision, final VcsStatus contentStatus);
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/package.html
new file mode 100644
index 0000000..73d29c0
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>VFS version control operations.</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/readme.html b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/readme.html
new file mode 100644
index 0000000..817da81
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/operations/vcs/readme.html
@@ -0,0 +1,27 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<html>
+ <body>
+ <p>
+ This package contains common interfaces for Version Control Systems such as
+ SVN, CVS, etc. <br />
+ The implementation of that interfaces it a system-specific deal and all
+ implementations are located in the corresponding packages for those concrete
+ systems.
+ </p>
+ </body>
+</html>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/package.html
new file mode 100644
index 0000000..fc34de6
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>The public VFS API.</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractFileName.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractFileName.java
new file mode 100644
index 0000000..13ed821
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractFileName.java
@@ -0,0 +1,575 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.NameScope;
+import org.apache.commons.vfs2.VFS;
+
+/**
+ * A default file name implementation.
+ */
+public abstract class AbstractFileName implements FileName
+{
+
+ private final String scheme;
+ private final String absPath;
+ private FileType type;
+
+ // Cached stuff
+ private String uri;
+ private String baseName;
+ private String rootUri;
+ private String extension;
+ private String decodedAbsPath;
+
+ private String key = null;
+
+ public AbstractFileName(final String scheme, final String absPath, final FileType type)
+ {
+ this.rootUri = null;
+ this.scheme = scheme;
+ this.type = type;
+ if (absPath != null && absPath.length() > 0)
+ {
+ if (absPath.length() > 1 && absPath.endsWith("/"))
+ {
+ this.absPath = absPath.substring(0, absPath.length() - 1);
+ }
+ else
+ {
+ this.absPath = absPath;
+ }
+ }
+ else
+ {
+ this.absPath = ROOT_PATH;
+ }
+ }
+
+ @Override
+ public boolean equals(final Object o)
+ {
+ if (this == o)
+ {
+ return true;
+ }
+ if (o == null || getClass() != o.getClass())
+ {
+ return false;
+ }
+
+ final AbstractFileName that = (AbstractFileName) o;
+
+ return getKey().equals(that.getKey());
+ }
+
+ @Override
+ public int hashCode()
+ {
+ return getKey().hashCode();
+ }
+
+ /**
+ * Implement Comparable.
+ *
+ * @param obj another abstract filename
+ * @return negative number if less than, 0 if equal, positive if greater than.
+ */
+ @Override
+ public int compareTo(final FileName obj)
+ {
+ final AbstractFileName name = (AbstractFileName) obj;
+ return getKey().compareTo(name.getKey());
+ }
+
+ /**
+ * Returns the URI of the file.
+ * @return the FileName as a URI.
+ */
+ @Override
+ public String toString()
+ {
+ return getURI();
+ }
+
+ /**
+ * Factory method for creating name instances.
+ * @param absPath The absolute path.
+ * @param type The FileType.
+ * @return The FileName.
+ */
+ public abstract FileName createName(String absPath, FileType type);
+
+ /**
+ * Builds the root URI for this file name. Note that the root URI must not
+ * end with a separator character.
+ * @param buffer A StringBuilder to use to construct the URI.
+ * @param addPassword true if the password should be added, false otherwise.
+ */
+ protected abstract void appendRootUri(StringBuilder buffer, boolean addPassword);
+
+ /**
+ * Returns the base name of the file.
+ * @return The base name of the file.
+ */
+ @Override
+ public String getBaseName()
+ {
+ if (baseName == null)
+ {
+ final int idx = getPath().lastIndexOf(SEPARATOR_CHAR);
+ if (idx == -1)
+ {
+ baseName = getPath();
+ }
+ else
+ {
+ baseName = getPath().substring(idx + 1);
+ }
+ }
+
+ return baseName;
+ }
+
+ /**
+ * Returns the absolute path of the file, relative to the root of the
+ * file system that the file belongs to.
+ * @return The path String.
+ */
+ @Override
+ public String getPath()
+ {
+ if (VFS.isUriStyle())
+ {
+ return absPath + getUriTrailer();
+ }
+ return absPath;
+ }
+
+ protected String getUriTrailer()
+ {
+ return getType().hasChildren() ? "/" : "";
+ }
+
+ /**
+ * Returns the decoded path.
+ * @return The decoded path String.
+ * @throws FileSystemException If an error occurs.
+ */
+ @Override
+ public String getPathDecoded() throws FileSystemException
+ {
+ if (decodedAbsPath == null)
+ {
+ decodedAbsPath = UriParser.decode(getPath());
+ }
+
+ return decodedAbsPath;
+ }
+
+ /**
+ * Returns the name of the parent of the file.
+ * @return the FileName of the parent.
+ */
+ @Override
+ public FileName getParent()
+ {
+ final String parentPath;
+ final int idx = getPath().lastIndexOf(SEPARATOR_CHAR);
+ if (idx == -1 || idx == getPath().length() - 1)
+ {
+ // No parent
+ return null;
+ }
+ else if (idx == 0)
+ {
+ // Root is the parent
+ parentPath = SEPARATOR;
+ }
+ else
+ {
+ parentPath = getPath().substring(0, idx);
+ }
+ return createName(parentPath, FileType.FOLDER);
+ }
+
+ /**
+ * find the root of the filesystem.
+ * @return The root FileName.
+ */
+ @Override
+ public FileName getRoot()
+ {
+ FileName root = this;
+ while (root.getParent() != null)
+ {
+ root = root.getParent();
+ }
+
+ return root;
+ }
+
+ /**
+ * Returns the URI scheme of this file.
+ * @return The protocol used to access the file.
+ */
+ @Override
+ public String getScheme()
+ {
+ return scheme;
+ }
+
+ /**
+ * Returns the absolute URI of the file.
+ * @return The absolute URI of the file.
+ */
+ @Override
+ public String getURI()
+ {
+ if (uri == null)
+ {
+ uri = createURI();
+ }
+ return uri;
+ }
+
+ protected String createURI()
+ {
+ return createURI(false, true);
+ }
+
+ /**
+ * Create a path that does not use the FileType since that field is not immutable.
+ * @return The key.
+ */
+ private String getKey()
+ {
+ if (key == null)
+ {
+ key = getURI();
+ }
+ return key;
+ }
+
+ /**
+ * Returns the URI without a password.
+ *
+ * @return Returns the URI without a password.
+ */
+ @Override
+ public String getFriendlyURI()
+ {
+ return createURI(false, false);
+ }
+
+ private String createURI(final boolean useAbsolutePath, final boolean usePassword)
+ {
+ final StringBuilder buffer = new StringBuilder();
+ appendRootUri(buffer, usePassword);
+ buffer.append(useAbsolutePath ? absPath : getPath());
+ return buffer.toString();
+ }
+
+
+ /**
+ * Converts a file name to a relative name, relative to this file name.
+ * @param name The FileName.
+ * @return The relative path to the file.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public String getRelativeName(final FileName name) throws FileSystemException
+ {
+ final String path = name.getPath();
+
+ // Calculate the common prefix
+ final int basePathLen = getPath().length();
+ final int pathLen = path.length();
+
+ // Deal with root
+ if (basePathLen == 1 && pathLen == 1)
+ {
+ return ".";
+ }
+ else if (basePathLen == 1)
+ {
+ return path.substring(1);
+ }
+
+ final int maxlen = Math.min(basePathLen, pathLen);
+ int pos = 0;
+ for (; pos < maxlen && getPath().charAt(pos) == path.charAt(pos); pos++)
+ {
+ }
+
+ if (pos == basePathLen && pos == pathLen)
+ {
+ // Same names
+ return ".";
+ }
+ else if (pos == basePathLen && pos < pathLen && path.charAt(pos) == SEPARATOR_CHAR)
+ {
+ // A descendent of the base path
+ return path.substring(pos + 1);
+ }
+
+ // Strip the common prefix off the path
+ final StringBuilder buffer = new StringBuilder();
+ if (pathLen > 1 && (pos < pathLen || getPath().charAt(pos) != SEPARATOR_CHAR))
+ {
+ // Not a direct ancestor, need to back up
+ pos = getPath().lastIndexOf(SEPARATOR_CHAR, pos);
+ buffer.append(path.substring(pos));
+ }
+
+ // Prepend a '../' for each element in the base path past the common
+ // prefix
+ buffer.insert(0, "..");
+ pos = getPath().indexOf(SEPARATOR_CHAR, pos + 1);
+ while (pos != -1)
+ {
+ buffer.insert(0, "../");
+ pos = getPath().indexOf(SEPARATOR_CHAR, pos + 1);
+ }
+
+ return buffer.toString();
+ }
+
+ /**
+ * Returns the root URI of the file system this file belongs to.
+ * @return The URI of the root.
+ */
+ @Override
+ public String getRootURI()
+ {
+ if (rootUri == null)
+ {
+ final StringBuilder buffer = new StringBuilder();
+ appendRootUri(buffer, true);
+ buffer.append(SEPARATOR_CHAR);
+ rootUri = buffer.toString().intern();
+ }
+ return rootUri;
+ }
+
+ /**
+ * Returns the depth of this file name, within its file system.
+ * @return The depth of the file name.
+ */
+ @Override
+ public int getDepth()
+ {
+ final int len = getPath().length();
+ if (len == 0 || len == 1 && getPath().charAt(0) == SEPARATOR_CHAR)
+ {
+ return 0;
+ }
+ int depth = 1;
+ for (int pos = 0; pos > -1 && pos < len; depth++)
+ {
+ pos = getPath().indexOf(SEPARATOR_CHAR, pos + 1);
+ }
+ return depth;
+ }
+
+ /**
+ * Returns the extension of this file name.
+ * @return The file extension.
+ */
+ @Override
+ public String getExtension()
+ {
+ if (extension == null)
+ {
+ getBaseName();
+ final int pos = baseName.lastIndexOf('.');
+ // if ((pos == -1) || (pos == baseName.length() - 1))
+ // imario@ops.co.at: Review of patch from adagoubard@chello.nl
+ // do not treat filenames like
+ // .bashrc c:\windows\.java c:\windows\.javaws c:\windows\.jedit c:\windows\.appletviewer
+ // as extension
+ if (pos < 1 || pos == baseName.length() - 1)
+ {
+ // No extension
+ extension = "";
+ }
+ else
+ {
+ extension = baseName.substring(pos + 1).intern();
+ }
+ }
+ return extension;
+ }
+
+ /**
+ * Determines if another file name is an ancestor of this file name.
+ * @param ancestor The FileName to check.
+ * @return true if the FileName is an ancestor, false otherwise.
+ */
+ @Override
+ public boolean isAncestor(final FileName ancestor)
+ {
+ if (!ancestor.getRootURI().equals(getRootURI()))
+ {
+ return false;
+ }
+ return checkName(ancestor.getPath(), getPath(), NameScope.DESCENDENT);
+ }
+
+ /**
+ * Determines if another file name is a descendent of this file name.
+ * @param descendent The FileName to check.
+ * @return true if the FileName is a descendent, false otherwise.
+ */
+ @Override
+ public boolean isDescendent(final FileName descendent)
+ {
+ return isDescendent(descendent, NameScope.DESCENDENT);
+ }
+
+ /**
+ * Determines if another file name is a descendent of this file name.
+ * @param descendent The FileName to check.
+ * @param scope The NameScope.
+ * @return true if the FileName is a descendent, false otherwise.
+ */
+ @Override
+ public boolean isDescendent(final FileName descendent,
+ final NameScope scope)
+ {
+ if (!descendent.getRootURI().equals(getRootURI()))
+ {
+ return false;
+ }
+ return checkName(getPath(), descendent.getPath(), scope);
+ }
+
+ /**
+ * Checks if this file name is a name for a regular file by using its type.
+ *
+ * @return true if this file is a regular file.
+ * @throws FileSystemException may be thrown by subclasses.
+ * @see #getType()
+ * @see FileType#FILE
+ */
+ @Override
+ public boolean isFile() throws FileSystemException
+ {
+ // Use equals instead of == to avoid any class loader worries.
+ return FileType.FILE.equals(this.getType());
+ }
+
+ /**
+ * Returns the requested or current type of this name.
+ * <p>
+ * The "requested" type is the one determined during resolving the name.
+ * n this case the name is a {@link FileType#FOLDER} if it ends with an "/" else
+ * it will be a {@link FileType#FILE}.
+ * <p>
+ * Once attached it will be changed to reflect the real type of this resource.
+ *
+ * @return {@link FileType#FOLDER} or {@link FileType#FILE}
+ */
+ @Override
+ public FileType getType()
+ {
+ return type;
+ }
+
+ /**
+ * Sets the type of this file e.g. when it will be attached.
+ *
+ * @param type {@link FileType#FOLDER} or {@link FileType#FILE}
+ * @throws FileSystemException if an error occurs.
+ */
+ void setType(final FileType type) throws FileSystemException
+ {
+ if (type != FileType.FOLDER && type != FileType.FILE && type != FileType.FILE_OR_FOLDER)
+ {
+ throw new FileSystemException("vfs.provider/filename-type.error");
+ }
+
+ this.type = type;
+ }
+
+ /**
+ * Checks whether a path fits in a particular scope of another path.
+ *
+ * @param basePath An absolute, normalised path.
+ * @param path An absolute, normalised path.
+ * @param scope The NameScope.
+ * @return true if the path fits in the scope, false otherwise.
+ */
+ public static boolean checkName(final String basePath,
+ final String path,
+ final NameScope scope)
+ {
+ if (scope == NameScope.FILE_SYSTEM)
+ {
+ // All good
+ return true;
+ }
+
+ if (!path.startsWith(basePath))
+ {
+ return false;
+ }
+
+ int baseLen = basePath.length();
+ if (VFS.isUriStyle())
+ {
+ // strip the trailing "/"
+ baseLen--;
+ }
+
+ if (scope == NameScope.CHILD)
+ {
+ if (path.length() == baseLen
+ || baseLen > 1 && path.charAt(baseLen) != SEPARATOR_CHAR
+ || path.indexOf(SEPARATOR_CHAR, baseLen + 1) != -1)
+ {
+ return false;
+ }
+ }
+ else if (scope == NameScope.DESCENDENT)
+ {
+ if (path.length() == baseLen
+ || baseLen > 1 && path.charAt(baseLen) != SEPARATOR_CHAR)
+ {
+ return false;
+ }
+ }
+ else if (scope == NameScope.DESCENDENT_OR_SELF)
+ {
+ if (baseLen > 1
+ && path.length() > baseLen
+ && path.charAt(baseLen) != SEPARATOR_CHAR)
+ {
+ return false;
+ }
+ }
+ else if (scope != NameScope.FILE_SYSTEM)
+ {
+ throw new IllegalArgumentException();
+ }
+
+ return true;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractFileNameParser.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractFileNameParser.java
new file mode 100644
index 0000000..b7815b5
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractFileNameParser.java
@@ -0,0 +1,29 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+/**
+ * Provides methods to parse a filename into a {@link org.apache.commons.vfs2.FileName}.
+ */
+public abstract class AbstractFileNameParser implements FileNameParser
+{
+ @Override
+ public boolean encodeCharacter(final char ch)
+ {
+ return ch == '%';
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractFileObject.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractFileObject.java
new file mode 100644
index 0000000..db7542f
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractFileObject.java
@@ -0,0 +1,2125 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.security.AccessController;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+import java.security.cert.Certificate;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileContent;
+import org.apache.commons.vfs2.FileContentInfoFactory;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileNotFolderException;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSelector;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.FileUtil;
+import org.apache.commons.vfs2.NameScope;
+import org.apache.commons.vfs2.RandomAccessContent;
+import org.apache.commons.vfs2.Selectors;
+import org.apache.commons.vfs2.operations.DefaultFileOperations;
+import org.apache.commons.vfs2.operations.FileOperations;
+import org.apache.commons.vfs2.util.FileObjectUtils;
+import org.apache.commons.vfs2.util.RandomAccessMode;
+
+/**
+ * A partial file object implementation.
+ *
+ * @param <AFS> An AbstractFileSystem subclass
+ */
+public abstract class AbstractFileObject<AFS extends AbstractFileSystem> implements FileObject
+{
+ /*
+ * TODO - Chop this class up - move all the protected methods to several
+ * interfaces, so that structure and content can be separately overridden.
+ *
+ * TODO - Check caps in methods like getChildren(), etc, and give better error messages
+ * (eg 'this file type does not support listing children', vs 'this is not a folder')
+ */
+
+ private static final FileName[] EMPTY_FILE_ARRAY = {};
+
+ private static final int INITIAL_LIST_SIZE = 5;
+
+ private final AbstractFileName fileName;
+ private final AFS fs;
+
+ private FileContent content;
+ // Cached info
+ private boolean attached;
+ private FileType type;
+
+ private FileObject parent;
+ // Changed to hold only the name of the children and let the object
+ // go into the global files cache
+ // private FileObject[] children;
+ private FileName[] children;
+
+ private List<Object> objects;
+
+ /**
+ * FileServices instance.
+ */
+ private FileOperations operations;
+
+ /**
+ *
+ * @param name the file name - muse be an instance of {@link AbstractFileName}
+ * @param fs the file system
+ * @throws ClassCastException if {@code name} is not an instance of {@link AbstractFileName}
+ */
+ protected AbstractFileObject(final AbstractFileName name,
+ final AFS fs)
+ {
+ this.fileName = name;
+ this.fs = fs;
+ fs.fileObjectHanded(this);
+ }
+
+ /**
+ * Traverses a file.
+ */
+ private static void traverse(final DefaultFileSelectorInfo fileInfo,
+ final FileSelector selector,
+ final boolean depthwise,
+ final List<FileObject> selected)
+ throws Exception
+ {
+ // Check the file itself
+ final FileObject file = fileInfo.getFile();
+ final int index = selected.size();
+
+ // If the file is a folder, traverse it
+ if (file.getType().hasChildren() && selector.traverseDescendents(fileInfo))
+ {
+ final int curDepth = fileInfo.getDepth();
+ fileInfo.setDepth(curDepth + 1);
+
+ // Traverse the children
+ final FileObject[] children = file.getChildren();
+ for (final FileObject child : children)
+ {
+ fileInfo.setFile(child);
+ traverse(fileInfo, selector, depthwise, selected);
+ }
+
+ fileInfo.setFile(file);
+ fileInfo.setDepth(curDepth);
+ }
+
+ // Add the file if doing depthwise traversal
+ if (selector.includeFile(fileInfo))
+ {
+ if (depthwise)
+ {
+ // Add this file after its descendants
+ selected.add(file);
+ }
+ else
+ {
+ // Add this file before its descendants
+ selected.add(index, file);
+ }
+ }
+ }
+
+ /**
+ * Attaches to the file.
+ * @throws FileSystemException if an error occurs.
+ */
+ private void attach() throws FileSystemException
+ {
+ synchronized (fs)
+ {
+ if (attached)
+ {
+ return;
+ }
+
+ try
+ {
+ // Attach and determine the file type
+ doAttach();
+ attached = true;
+ // now the type could already be injected by doAttach (e.g from parent to child)
+
+ /* VFS-210: determine the type when really asked fore
+ if (type == null)
+ {
+ setFileType(doGetType());
+ }
+ if (type == null)
+ {
+ setFileType(FileType.IMAGINARY);
+ }
+ */
+ }
+ catch (final Exception exc)
+ {
+ throw new FileSystemException("vfs.provider/get-type.error", exc, fileName);
+ }
+
+ // fs.fileAttached(this);
+ }
+ }
+
+ /**
+ * Queries the object if a simple rename to the filename of {@code newfile}
+ * is possible.
+ *
+ * @param newfile the new filename
+ * @return true if rename is possible
+ */
+ @Override
+ public boolean canRenameTo(final FileObject newfile)
+ {
+ return fs == newfile.getFileSystem();
+ }
+
+ /**
+ * Notifies the file that its children have changed.
+ * @param childName The name of the child.
+ * @param newType The type of the child.
+ * @throws Exception if an error occurs.
+ */
+ protected void childrenChanged(final FileName childName, final FileType newType) throws Exception
+ {
+ // TODO - this may be called when not attached
+
+ if (children != null && childName != null && newType != null)
+ {
+ // TODO - figure out if children[] can be replaced by list
+ final ArrayList<FileName> list = new ArrayList<FileName>(Arrays.asList(children));
+ if (newType.equals(FileType.IMAGINARY))
+ {
+ list.remove(childName);
+ }
+ else
+ {
+ list.add(childName);
+ }
+ children = new FileName[list.size()];
+ list.toArray(children);
+ }
+
+ // removeChildrenCache();
+ onChildrenChanged(childName, newType);
+ }
+
+ /**
+ * Closes this file, and its content.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public void close() throws FileSystemException
+ {
+ FileSystemException exc = null;
+
+ // Close the content
+ if (content != null)
+ {
+ try
+ {
+ content.close();
+ content = null;
+ }
+ catch (final FileSystemException e)
+ {
+ exc = e;
+ }
+ }
+
+ // Detach from the file
+ try
+ {
+ detach();
+ }
+ catch (final Exception e)
+ {
+ exc = new FileSystemException("vfs.provider/close.error", fileName, e);
+ }
+
+ if (exc != null)
+ {
+ throw exc;
+ }
+ }
+
+ /**
+ * Compares two FileObjects (ignores case).
+ *
+ * @param file
+ * the object to compare.
+ * @return a negative integer, zero, or a positive integer when this object is less than, equal to, or greater than
+ * the given object.
+ */
+ @Override
+ public int compareTo(final FileObject file)
+ {
+ if (file == null)
+ {
+ return 1;
+ }
+ return this.toString().compareToIgnoreCase(file.toString());
+ }
+
+ /**
+ * Copies another file to this file.
+ *
+ * @param file The FileObject to copy.
+ * @param selector The FileSelector.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public void copyFrom(final FileObject file, final FileSelector selector)
+ throws FileSystemException
+ {
+ if (!file.exists())
+ {
+ throw new FileSystemException("vfs.provider/copy-missing-file.error", file);
+ }
+
+ // Locate the files to copy across
+ final ArrayList<FileObject> files = new ArrayList<FileObject>();
+ file.findFiles(selector, false, files);
+
+ // Copy everything across
+ for (final FileObject srcFile : files)
+ {
+ // Determine the destination file
+ final String relPath = file.getName().getRelativeName(srcFile.getName());
+ final FileObject destFile = resolveFile(relPath, NameScope.DESCENDENT_OR_SELF);
+
+ // Clean up the destination file, if necessary
+ if (destFile.exists() && destFile.getType() != srcFile.getType())
+ {
+ // The destination file exists, and is not of the same type,
+ // so delete it
+ // TODO - add a pluggable policy for deleting and overwriting existing files
+ destFile.deleteAll();
+ }
+
+ // Copy across
+ try
+ {
+ if (srcFile.getType().hasContent())
+ {
+ FileUtil.copyContent(srcFile, destFile);
+ }
+ else if (srcFile.getType().hasChildren())
+ {
+ destFile.createFolder();
+ }
+ }
+ catch (final IOException e)
+ {
+ throw new FileSystemException("vfs.provider/copy-file.error", e, srcFile, destFile);
+ }
+ }
+ }
+
+ /**
+ * Creates this file, if it does not exist.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public void createFile() throws FileSystemException
+ {
+ synchronized (fs)
+ {
+ try
+ {
+ // VFS-210: We do not want to trunc any existing file, checking for its existence is
+ // still required
+ if (exists() && !isFile())
+ {
+ throw new FileSystemException("vfs.provider/create-file.error", fileName);
+ }
+
+ if (!exists())
+ {
+ getOutputStream().close();
+ endOutput();
+ }
+ }
+ catch (final RuntimeException re)
+ {
+ throw re;
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("vfs.provider/create-file.error", fileName, e);
+ }
+ }
+ }
+
+ /**
+ * Creates this folder, if it does not exist. Also creates any ancestor
+ * files which do not exist.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public void createFolder() throws FileSystemException
+ {
+ synchronized (fs)
+ {
+ // VFS-210: we create a folder only if it does not already exist. So this check should be safe.
+ if (getType().hasChildren())
+ {
+ // Already exists as correct type
+ return;
+ }
+ if (getType() != FileType.IMAGINARY)
+ {
+ throw new FileSystemException("vfs.provider/create-folder-mismatched-type.error", fileName);
+ }
+ /* VFS-210: checking for writeable is not always possible as the security constraint might
+ be more complex
+ if (!isWriteable())
+ {
+ throw new FileSystemException("vfs.provider/create-folder-read-only.error", name);
+ }
+ */
+
+ // Traverse up the hierarchy and make sure everything is a folder
+ final FileObject parent = getParent();
+ if (parent != null)
+ {
+ parent.createFolder();
+ }
+
+ try
+ {
+ // Create the folder
+ doCreateFolder();
+
+ // Update cached info
+ handleCreate(FileType.FOLDER);
+ }
+ catch (final RuntimeException re)
+ {
+ throw re;
+ }
+ catch (final Exception exc)
+ {
+ throw new FileSystemException("vfs.provider/create-folder.error", fileName, exc);
+ }
+ }
+ }
+
+ /**
+ * Deletes this file.
+ * <p>
+ * TODO - This will not fail if this is a non-empty folder.
+ *
+ * @return true if this object has been deleted
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public boolean delete() throws FileSystemException
+ {
+ return delete(Selectors.SELECT_SELF) > 0;
+ }
+
+ /**
+ * Deletes this file, and all children matching the {@code selector}.
+ *
+ * @param selector The FileSelector.
+ * @return the number of deleted files.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public int delete(final FileSelector selector) throws FileSystemException
+ {
+ int nuofDeleted = 0;
+
+ /* VFS-210
+ if (getType() == FileType.IMAGINARY)
+ {
+ // File does not exist
+ return nuofDeleted;
+ }
+ */
+
+ // Locate all the files to delete
+ final ArrayList<FileObject> files = new ArrayList<FileObject>();
+ findFiles(selector, true, files);
+
+ // Delete 'em
+ final int count = files.size();
+ for (int i = 0; i < count; i++)
+ {
+ final AbstractFileObject file = FileObjectUtils.getAbstractFileObject(files.get(i));
+ // file.attach();
+
+ // VFS-210: It seems impossible to me that findFiles will return a list with hidden files/directories
+ // in it, else it would not be hidden. Checking for the file-type seems ok in this case
+ // If the file is a folder, make sure all its children have been deleted
+ if (file.getType().hasChildren() && file.getChildren().length != 0)
+ {
+ // Skip - as the selector forced us not to delete all files
+ continue;
+ }
+
+ // Delete the file
+ if (file.deleteSelf())
+ {
+ nuofDeleted++;
+ }
+ }
+
+ return nuofDeleted;
+ }
+
+ /**
+ * Deletes this file and all children. Shorthand for {@code delete(Selectors.SELECT_ALL)}
+ *
+ * @return the number of deleted files.
+ * @throws FileSystemException if an error occurs.
+ * @see #delete(FileSelector)
+ * @see Selectors#SELECT_ALL
+ */
+ @Override
+ public int deleteAll() throws FileSystemException
+ {
+ return this.delete(Selectors.SELECT_ALL);
+ }
+
+ /**
+ * Deletes this file, once all its children have been deleted
+ *
+ * @return true if this file has been deleted
+ * @throws FileSystemException if an error occurs.
+ */
+ private boolean deleteSelf() throws FileSystemException
+ {
+ synchronized (fs)
+ {
+ //Its possible to delete a read-only file if you have write-execute access to the directory
+
+ /* VFS-210
+ if (getType() == FileType.IMAGINARY)
+ {
+ // File does not exist
+ return false;
+ }
+ */
+
+ try
+ {
+ // Delete the file
+ doDelete();
+
+ // Update cached info
+ handleDelete();
+ }
+ catch (final RuntimeException re)
+ {
+ throw re;
+ }
+ catch (final Exception exc)
+ {
+ throw new FileSystemException("vfs.provider/delete.error", exc, fileName);
+ }
+
+ return true;
+ }
+ }
+
+ /**
+ * Detaches this file, invalidating all cached info. This will force
+ * a call to {@link #doAttach} next time this file is used.
+ * @throws Exception if an error occurs.
+ */
+ private void detach() throws Exception
+ {
+ synchronized (fs)
+ {
+ if (attached)
+ {
+ try
+ {
+ doDetach();
+ }
+ finally
+ {
+ attached = false;
+ setFileType(null);
+ parent = null;
+
+ // fs.fileDetached(this);
+
+ removeChildrenCache();
+ // children = null;
+ }
+ }
+ }
+ }
+
+ /**
+ * Attaches this file object to its file resource.
+ * <p>
+ * This method is called before any of the doBlah() or onBlah() methods.
+ * Sub-classes can use this method to perform lazy initialisation.
+ * <p>
+ * This implementation does nothing.
+ *
+ * @throws Exception if an error occurs.
+ */
+ protected void doAttach() throws Exception
+ {
+ }
+
+ /**
+ * Create a FileContent implementation.
+ * @return The FileContent.
+ * @throws FileSystemException if an error occurs.
+ * @since 2.0
+ */
+ protected FileContent doCreateFileContent() throws FileSystemException
+ {
+ return new DefaultFileContent(this, getFileContentInfoFactory());
+ }
+
+ /**
+ * Creates this file as a folder. Is only called when:
+ * <ul>
+ * <li>{@link #doGetType} returns {@link FileType#IMAGINARY}.</li>
+ * <li>The parent folder exists and is writeable, or this file is the
+ * root of the file system.</li>
+ * </ul>
+ * This implementation throws an exception.
+ *
+ * @throws Exception if an error occurs.
+ */
+ protected void doCreateFolder() throws Exception
+ {
+ throw new FileSystemException("vfs.provider/create-folder-not-supported.error");
+ }
+
+ /**
+ * Deletes the file. Is only called when:
+ * <ul>
+ * <li>{@link #doGetType} does not return {@link FileType#IMAGINARY}.</li>
+ * <li>{@link #doIsWriteable} returns true.</li>
+ * <li>This file has no children, if a folder.</li>
+ * </ul>
+ * This implementation throws an exception.
+
+ * @throws Exception if an error occurs.
+ */
+ protected void doDelete() throws Exception
+ {
+ throw new FileSystemException("vfs.provider/delete-not-supported.error");
+ }
+
+ /**
+ * Detaches this file object from its file resource.
+ * <p>
+ * Called when this file is closed. Note that the file object may be
+ * reused later, so should be able to be reattached.
+ * <p>
+ * This implementation does nothing.
+ *
+ * @throws Exception if an error occurs.
+ */
+ protected void doDetach() throws Exception
+ {
+ }
+
+ /**
+ * Returns the attributes of this file. Is only called if {@link #doGetType}
+ * does not return {@link FileType#IMAGINARY}.
+ * <p>
+ * This implementation always returns an empty map.
+ *
+ * @return The attributes of the file.
+ * @throws Exception if an error occurs.
+ */
+ protected Map<String, Object> doGetAttributes() throws Exception
+ {
+ return Collections.emptyMap();
+ }
+
+ /**
+ * Returns the certificates used to sign this file. Is only called if
+ * {@link #doGetType} does not return {@link FileType#IMAGINARY}.
+ * <p>
+ * This implementation always returns null.
+ *
+ * @return The certificates used to sign the file.
+ * @throws Exception if an error occurs.
+ */
+ protected Certificate[] doGetCertificates() throws Exception
+ {
+ return null;
+ }
+
+ /**
+ * Returns the size of the file content (in bytes). Is only called if
+ * {@link #doGetType} returns {@link FileType#FILE}.
+ * @return The size of the file in bytes.
+ * @throws Exception if an error occurs.
+ */
+ protected abstract long doGetContentSize() throws Exception;
+
+ /**
+ * Creates an input stream to read the file content from. Is only called
+ * if {@link #doGetType} returns {@link FileType#FILE}.
+ * <p>
+ * It is guaranteed that there are no open output streams for this file
+ * when this method is called.
+ * <p>
+ * The returned stream does not have to be buffered.
+ *
+ * @return An InputStream to read the file content.
+ * @throws Exception if an error occurs.
+ */
+ protected abstract InputStream doGetInputStream() throws Exception;
+
+ /**
+ * Returns the last modified time of this file. Is only called if
+ * {@link #doGetType} does not return {@link FileType#IMAGINARY}.
+ * <p>
+ * This implementation throws an exception.
+ *
+ * @return The last modification time.
+ * @throws Exception if an error occurs.
+ */
+ protected long doGetLastModifiedTime() throws Exception
+ {
+ throw new FileSystemException("vfs.provider/get-last-modified-not-supported.error");
+ }
+
+ /**
+ * Creates an output stream to write the file content to. Is only
+ * called if:
+ * <ul>
+ * <li>{@link #doIsWriteable} returns true.
+ * <li>{@link #doGetType} returns {@link FileType#FILE}, or
+ * {@link #doGetType} returns {@link FileType#IMAGINARY}, and the file's
+ * parent exists and is a folder.
+ * </ul>
+ * It is guaranteed that there are no open stream (input or output) for
+ * this file when this method is called.
+ * <p>
+ * The returned stream does not have to be buffered.
+ * <p>
+ * This implementation throws an exception.
+ *
+ * @param bAppend true if the file should be appended to, false if it should be overwritten.
+ * @return An OutputStream to write to the file.
+ * @throws Exception if an error occurs.
+ */
+ protected OutputStream doGetOutputStream(final boolean bAppend) throws Exception
+ {
+ throw new FileSystemException("vfs.provider/write-not-supported.error");
+ }
+
+ /**
+ * Creates access to the file for random i/o. Is only called
+ * if {@link #doGetType} returns {@link FileType#FILE}.
+ * <p>
+ * It is guaranteed that there are no open output streams for this file
+ * when this method is called.
+ *
+ * @param mode The mode to access the file.
+ * @return The RandomAccessContext.
+ * @throws Exception if an error occurs.
+ */
+ protected RandomAccessContent doGetRandomAccessContent(final RandomAccessMode mode) throws Exception
+ {
+ throw new FileSystemException("vfs.provider/random-access-not-supported.error");
+ }
+
+ /**
+ * Determines the type of this file. Must not return null. The return
+ * value of this method is cached, so the implementation can be expensive.
+ * @return the type of the file.
+ * @throws Exception if an error occurs.
+ */
+ protected abstract FileType doGetType() throws Exception;
+
+ /**
+ * Determines if this file is executable. Is only called if {@link #doGetType}
+ * does not return {@link FileType#IMAGINARY}.
+ * <p>
+ * This implementation always returns false.
+ *
+ * @return true if the file is executable, false otherwise.
+ * @throws Exception if an error occurs.
+ */
+ protected boolean doIsExecutable() throws Exception
+ {
+ return false;
+ }
+
+ /**
+ * Determines if this file is hidden. Is only called if {@link #doGetType}
+ * does not return {@link FileType#IMAGINARY}.
+ * <p>
+ * This implementation always returns false.
+ *
+ * @return true if the file is hidden, false otherwise.
+ * @throws Exception if an error occurs.
+ */
+ protected boolean doIsHidden() throws Exception
+ {
+ return false;
+ }
+
+ /**
+ * Determines if this file can be read. Is only called if {@link #doGetType}
+ * does not return {@link FileType#IMAGINARY}.
+ * <p>
+ * This implementation always returns true.
+ *
+ * @return true if the file is readable, false otherwise.
+ * @throws Exception if an error occurs.
+ */
+ protected boolean doIsReadable() throws Exception
+ {
+ return true;
+ }
+
+ /**
+ * Checks if this fileObject is the same file as {@code destFile} just with a different
+ * name. E.g. for case insensitive filesystems like windows.
+ *
+ * @param destFile The file to compare to.
+ * @return true if the FileObjects are the same.
+ * @throws FileSystemException if an error occurs.
+ */
+ protected boolean doIsSameFile(final FileObject destFile) throws FileSystemException
+ {
+ return false;
+ }
+
+ /**
+ * Determines if this file can be written to. Is only called if
+ * {@link #doGetType} does not return {@link FileType#IMAGINARY}.
+ * <p>
+ * This implementation always returns true.
+ *
+ * @return true if the file is writable.
+ * @throws Exception if an error occurs.
+ */
+ protected boolean doIsWriteable() throws Exception
+ {
+ return true;
+ }
+
+ /**
+ * Lists the children of this file. Is only called if {@link #doGetType}
+ * returns {@link FileType#FOLDER}. The return value of this method
+ * is cached, so the implementation can be expensive.
+ *
+ * @return a possible empty String array if the file is a directory or null or an exception if the
+ * file is not a directory or can't be read.
+ * @throws Exception if an error occurs.
+ */
+ protected abstract String[] doListChildren() throws Exception;
+
+ /**
+ * Lists the children of this file.
+ * <p>
+ * Is only called if {@link #doGetType} returns {@link FileType#FOLDER}.
+ * <p>
+ * The return value of this method is cached, so the implementation can be expensive.<br>
+ * Other than {@code doListChildren} you could return FileObject's to e.g. reinitialize the
+ * type of the file.
+ * <p>
+ * (Introduced for Webdav: "permission denied on resource" during getType())
+ *
+ * @return The children of this FileObject.
+ * @throws Exception if an error occurs.
+ */
+ protected FileObject[] doListChildrenResolved() throws Exception
+ {
+ return null;
+ }
+
+ /**
+ * Removes an attribute of this file.
+ * <p>
+ * Is only called if {@link #doGetType} does not return {@link FileType#IMAGINARY}.
+ * <p>
+ * This implementation throws an exception.
+ *
+ * @param attrName The name of the attribute to remove.
+ * @throws Exception if an error occurs.
+ * @since 2.0
+ */
+ protected void doRemoveAttribute(final String attrName) throws Exception
+ {
+ throw new FileSystemException("vfs.provider/remove-attribute-not-supported.error");
+ }
+
+ /**
+ * Renames the file.
+ * <p>
+ * Is only called when:
+ * <ul>
+ * <li>{@link #doIsWriteable} returns true.</li>
+ * </ul>
+ * <p>
+ * This implementation throws an exception.
+ *
+ * @param newFile A FileObject with the new file name.
+ * @throws Exception if an error occurs.
+ */
+ protected void doRename(final FileObject newFile) throws Exception
+ {
+ throw new FileSystemException("vfs.provider/rename-not-supported.error");
+ }
+
+ /**
+ * Sets an attribute of this file.
+ * <p>
+ * Is only called if {@link #doGetType} does not return {@link FileType#IMAGINARY}.
+ * <p>
+ * This implementation throws an exception.
+ *
+ * @param attrName The attribute name.
+ * @param value The value to be associated with the attribute name.
+ * @throws Exception if an error occurs.
+ */
+ protected void doSetAttribute(final String attrName, final Object value) throws Exception
+ {
+ throw new FileSystemException("vfs.provider/set-attribute-not-supported.error");
+ }
+
+ /**
+ * Make the file executable.
+ * <p>
+ * Only called if {@link #doGetType} does not return {@link FileType#IMAGINARY}.
+ * <p>
+ * This implementation returns false.
+ *
+ * @param executable True to allow access, false to disallow.
+ * @param ownerOnly If {@code true}, the permission applies only to the owner; otherwise, it applies to everybody.
+ * @return true if the operation succeeded.
+ * @throws Exception Any Exception thrown is wrapped in FileSystemException.
+ * @see #setExecutable(boolean, boolean)
+ * @since 2.1
+ */
+ protected boolean doSetExecutable(final boolean executable, final boolean ownerOnly) throws Exception
+ {
+ return false;
+ }
+
+ /**
+ * Sets the last modified time of this file.
+ * <p>
+ * Is only called if {@link #doGetType} does not return {@link FileType#IMAGINARY}.
+ * <p>
+ * This implementation throws an exception.
+ *
+ * @param modtime The last modification time.
+ * @return true if the time was set.
+ * @throws Exception Any Exception thrown is wrapped in FileSystemException.
+ */
+ protected boolean doSetLastModifiedTime(final long modtime) throws Exception
+ {
+ throw new FileSystemException("vfs.provider/set-last-modified-not-supported.error");
+ }
+
+ /**
+ * Make the file or folder readable.
+ * <p>
+ * Only called if {@link #doGetType} does not return {@link FileType#IMAGINARY}.
+ * <p>
+ * This implementation returns false.
+ *
+ * @param readable
+ * True to allow access, false to disallow
+ * @param ownerOnly
+ * If {@code true}, the permission applies only to the owner; otherwise, it applies to everybody.
+ * @return true if the operation succeeded
+ * @throws Exception Any Exception thrown is wrapped in FileSystemException.
+ * @see #setReadable(boolean, boolean)
+ * @since 2.1
+ */
+ protected boolean doSetReadable(final boolean readable, final boolean ownerOnly) throws Exception
+ {
+ return false;
+ }
+
+ /**
+ * Make the file or folder writeable.
+ * <p>
+ * Only called if {@link #doGetType} does not return {@link FileType#IMAGINARY}.
+ *
+ * @param writable True to allow access, false to disallow
+ * @param ownerOnly If {@code true}, the permission applies only to the owner; otherwise, it applies to everybody.
+ * @return true if the operation succeeded
+ * @throws Exception Any Exception thrown is wrapped in FileSystemException.
+ * @see #setWritable(boolean, boolean)
+ * @since 2.1
+ */
+ protected boolean doSetWritable(final boolean writable, final boolean ownerOnly) throws Exception
+ {
+ return false;
+ }
+
+ /**
+ * Called when the output stream for this file is closed.
+ * @throws Exception if an error occurs.
+ */
+ protected void endOutput() throws Exception
+ {
+ if (getType() == FileType.IMAGINARY)
+ {
+ // File was created
+ handleCreate(FileType.FILE);
+ }
+ else
+ {
+ // File has changed
+ onChange();
+ }
+ }
+
+ /**
+ * Determines if the file exists.
+ * @return true if the file exists, false otherwise,
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public boolean exists() throws FileSystemException
+ {
+ return getType() != FileType.IMAGINARY;
+ }
+
+ private FileName[] extractNames(final FileObject[] objects)
+ {
+ if (objects == null)
+ {
+ return null;
+ }
+
+ final FileName[] names = new FileName[objects.length];
+ for (int iterObjects = 0; iterObjects < objects.length; iterObjects++)
+ {
+ names[iterObjects] = objects[iterObjects].getName();
+ }
+
+ return names;
+ }
+
+ @Override
+ protected void finalize() throws Throwable
+ {
+ fs.fileObjectDestroyed(this);
+
+ super.finalize();
+ }
+
+
+ /**
+ * Finds the set of matching descendants of this file, in depthwise
+ * order.
+ *
+ * @param selector The FileSelector.
+ * @return list of files or null if the base file (this object) do not exist
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileObject[] findFiles(final FileSelector selector) throws FileSystemException
+ {
+ final List<FileObject> list = this.listFiles(selector);
+ return list == null ? null : list.toArray(new FileObject[list.size()]);
+ }
+
+ /**
+ * Traverses the descendants of this file, and builds a list of selected
+ * files.
+ * @param selector The FileSelector.
+ * @param depthwise if true files are added after their descendants, before otherwise.
+ * @param selected A List of the located FileObjects.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public void findFiles(final FileSelector selector,
+ final boolean depthwise,
+ final List<FileObject> selected) throws FileSystemException
+ {
+ try
+ {
+ if (exists())
+ {
+ // Traverse starting at this file
+ final DefaultFileSelectorInfo info = new DefaultFileSelectorInfo();
+ info.setBaseFolder(this);
+ info.setDepth(0);
+ info.setFile(this);
+ traverse(info, selector, depthwise, selected);
+ }
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("vfs.provider/find-files.error", fileName, e);
+ }
+ }
+
+ /**
+ * Returns the file system this file belongs to.
+ * @return The FileSystem this file is associated with.
+ */
+ protected AFS getAbstractFileSystem()
+ {
+ return fs;
+ }
+
+ /**
+ * Returns a child of this file.
+ * @param name The name of the child to locate.
+ * @return The FileObject for the file or null if the child does not exist.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileObject getChild(final String name) throws FileSystemException
+ {
+ // TODO - use a hashtable when there are a large number of children
+ final FileObject[] children = getChildren();
+ for (final FileObject element : children)
+ {
+ final FileName child = element.getName();
+ // TODO - use a comparator to compare names
+ if (child.getBaseName().equals(name))
+ {
+ return resolveFile(child);
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns the children of the file.
+ * @return an array of FileObjects, one per child.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileObject[] getChildren() throws FileSystemException
+ {
+ synchronized (fs)
+ {
+ // VFS-210
+ if (!fs.hasCapability(Capability.LIST_CHILDREN))
+ {
+ throw new FileNotFolderException(fileName);
+ }
+
+ /* VFS-210
+ if (!getType().hasChildren())
+ {
+ throw new FileSystemException("vfs.provider/list-children-not-folder.error", name);
+ }
+ */
+ attach();
+
+ // Use cached info, if present
+ if (children != null)
+ {
+ return resolveFiles(children);
+ }
+
+ // allow the filesystem to return resolved children. e.g. prefill type for webdav
+ FileObject[] childrenObjects;
+ try
+ {
+ childrenObjects = doListChildrenResolved();
+ children = extractNames(childrenObjects);
+ }
+ catch (final FileSystemException exc)
+ {
+ // VFS-210
+ throw exc;
+ }
+ catch (final Exception exc)
+ {
+ throw new FileSystemException("vfs.provider/list-children.error", exc, fileName);
+ }
+
+ if (childrenObjects != null)
+ {
+ return childrenObjects;
+ }
+
+ // List the children
+ final String[] files;
+ try
+ {
+ files = doListChildren();
+ }
+ catch (final FileSystemException exc)
+ {
+ // VFS-210
+ throw exc;
+ }
+ catch (final Exception exc)
+ {
+ throw new FileSystemException("vfs.provider/list-children.error", exc, fileName);
+ }
+
+ if (files == null)
+ {
+ // VFS-210
+ // honor the new doListChildren contract
+ // return null;
+ throw new FileNotFolderException(fileName);
+ }
+ else if (files.length == 0)
+ {
+ // No children
+ children = EMPTY_FILE_ARRAY;
+ }
+ else
+ {
+ // Create file objects for the children
+ final FileName[] cache = new FileName[files.length];
+ for (int i = 0; i < files.length; i++)
+ {
+ final String file = files[i];
+ cache[i] = fs.getFileSystemManager().resolveName(fileName, file, NameScope.CHILD);
+ }
+ // VFS-285: only assign the children filenames after all of them have been
+ // resolved successfully to prevent an inconsistent internal state
+ children = cache;
+ }
+
+ return resolveFiles(children);
+ }
+ }
+
+ /**
+ * Returns the file's content.
+ * @return the FileContent for this FileObject.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileContent getContent() throws FileSystemException
+ {
+ synchronized (fs)
+ {
+ attach();
+ if (content == null)
+ {
+ content = doCreateFileContent();
+ }
+ return content;
+ }
+ }
+
+ /**
+ * create the filecontentinfo implementation.
+ * @return The FileContentInfoFactory.
+ */
+ protected FileContentInfoFactory getFileContentInfoFactory()
+ {
+ return fs.getFileSystemManager().getFileContentInfoFactory();
+ }
+
+ /**
+ * @return FileOperations interface that provides access to the operations
+ * API.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileOperations getFileOperations() throws FileSystemException
+ {
+ if (operations == null)
+ {
+ operations = new DefaultFileOperations(this);
+ }
+
+ return operations;
+ }
+
+ /**
+ * Returns the file system this file belongs to.
+ * @return The FileSystem this file is associated with.
+ */
+ @Override
+ public FileSystem getFileSystem()
+ {
+ return fs;
+ }
+
+ /**
+ * Returns an input stream to use to read the content of the file.
+ * @return The InputStream to access this file's content.
+ * @throws FileSystemException if an error occurs.
+ */
+ public InputStream getInputStream() throws FileSystemException
+ {
+ /* VFS-210
+ if (!getType().hasContent())
+ {
+ throw new FileSystemException("vfs.provider/read-not-file.error", name);
+ }
+ if (!isReadable())
+ {
+ throw new FileSystemException("vfs.provider/read-not-readable.error", name);
+ }
+ */
+
+ // Get the raw input stream
+ try
+ {
+ return doGetInputStream();
+ }
+ catch (final org.apache.commons.vfs2.FileNotFoundException exc)
+ {
+ throw new org.apache.commons.vfs2.FileNotFoundException(fileName, exc);
+ }
+ catch (final FileNotFoundException exc)
+ {
+ throw new org.apache.commons.vfs2.FileNotFoundException(fileName, exc);
+ }
+ catch (final FileSystemException exc)
+ {
+ throw exc;
+ }
+ catch (final Exception exc)
+ {
+ throw new FileSystemException("vfs.provider/read.error", fileName, exc);
+ }
+ }
+
+ /**
+ * Returns the name of the file.
+ *
+ * @return The FileName, never {@code null}.
+ */
+ @Override
+ public FileName getName()
+ {
+ return fileName;
+ }
+
+ /**
+ * Returns the receiver as a URI String for public display, like, without a
+ * password.
+ *
+ * @return A URI String without a password, never {@code null}.
+ */
+ @Override
+ public String getPublicURIString()
+ {
+ return fileName.getFriendlyURI();
+ }
+
+ /**
+ * Prepares this file for writing. Makes sure it is either a file,
+ * or its parent folder exists. Returns an output stream to use to
+ * write the content of the file to.
+ * @return An OutputStream where the new contents of the file can be written.
+ * @throws FileSystemException if an error occurs.
+ */
+ public OutputStream getOutputStream() throws FileSystemException
+ {
+ return getOutputStream(false);
+ }
+
+ /**
+ * Prepares this file for writing. Makes sure it is either a file,
+ * or its parent folder exists. Returns an output stream to use to
+ * write the content of the file to.<br>
+ *
+ * @param bAppend true when append to the file.<br>
+ * Note: If the underlying filesystem does not support appending,
+ * a FileSystemException is thrown.
+ * @return An OutputStream where the new contents of the file can be written.
+ * @throws FileSystemException if an error occurs; for example:<br>
+ * bAppend is true, and the underlying FileSystem does not support it
+ */
+ public OutputStream getOutputStream(final boolean bAppend) throws FileSystemException
+ {
+ /* VFS-210
+ if (getType() != FileType.IMAGINARY && !getType().hasContent())
+ {
+ throw new FileSystemException("vfs.provider/write-not-file.error", name);
+ }
+ if (!isWriteable())
+ {
+ throw new FileSystemException("vfs.provider/write-read-only.error", name);
+ }
+ */
+
+ if (bAppend && !fs.hasCapability(Capability.APPEND_CONTENT))
+ {
+ throw new FileSystemException("vfs.provider/write-append-not-supported.error", fileName);
+ }
+
+ if (getType() == FileType.IMAGINARY)
+ {
+// Does not exist - make sure parent does
+ final FileObject parent = getParent();
+ if (parent != null)
+ {
+ parent.createFolder();
+ }
+ }
+
+// Get the raw output stream
+ try
+ {
+ return doGetOutputStream(bAppend);
+ }
+ catch (final RuntimeException re)
+ {
+ throw re;
+ }
+ catch (final Exception exc)
+ {
+ throw new FileSystemException("vfs.provider/write.error", exc, fileName);
+ }
+ }
+
+ /**
+ * Returns the parent of the file.
+ * @return the parent FileObject.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileObject getParent() throws FileSystemException
+ {
+ if (this.compareTo(fs.getRoot()) == 0) // equals is not implemented :-/
+ {
+ if (fs.getParentLayer() == null)
+ {
+ // Root file has no parent
+ return null;
+ }
+ else
+ {
+ // Return the parent of the parent layer
+ return fs.getParentLayer().getParent();
+ }
+ }
+
+ synchronized (fs)
+ {
+ // Locate the parent of this file
+ if (parent == null)
+ {
+ FileName name = fileName.getParent();
+ if (name == null)
+ {
+ return null;
+ }
+ parent = fs.resolveFile(name);
+ }
+ return parent;
+ }
+ }
+
+ /**
+ * Returns an input/output stream to use to read and write the content of the file in and
+ * random manner.
+ * @param mode The RandomAccessMode.
+ * @return The RandomAccessContent.
+ * @throws FileSystemException if an error occurs.
+ */
+ public RandomAccessContent getRandomAccessContent(final RandomAccessMode mode) throws FileSystemException
+ {
+ /* VFS-210
+ if (!getType().hasContent())
+ {
+ throw new FileSystemException("vfs.provider/read-not-file.error", name);
+ }
+ */
+
+ if (mode.requestRead())
+ {
+ if (!fs.hasCapability(Capability.RANDOM_ACCESS_READ))
+ {
+ throw new FileSystemException("vfs.provider/random-access-read-not-supported.error");
+ }
+ if (!isReadable())
+ {
+ throw new FileSystemException("vfs.provider/read-not-readable.error", fileName);
+ }
+ }
+
+ if (mode.requestWrite())
+ {
+ if (!fs.hasCapability(Capability.RANDOM_ACCESS_WRITE))
+ {
+ throw new FileSystemException("vfs.provider/random-access-write-not-supported.error");
+ }
+ if (!isWriteable())
+ {
+ throw new FileSystemException("vfs.provider/write-read-only.error", fileName);
+ }
+ }
+
+ // Get the raw input stream
+ try
+ {
+ return doGetRandomAccessContent(mode);
+ }
+ catch (final Exception exc)
+ {
+ throw new FileSystemException("vfs.provider/random-access.error", fileName, exc);
+ }
+ }
+
+ /**
+ * Returns the file's type.
+ * @return The FileType.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileType getType() throws FileSystemException
+ {
+ synchronized (fs)
+ {
+ attach();
+
+ // VFS-210: get the type only if requested for
+ try
+ {
+ if (type == null)
+ {
+ setFileType(doGetType());
+ }
+ if (type == null)
+ {
+ setFileType(FileType.IMAGINARY);
+ }
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("vfs.provider/get-type.error", e, fileName);
+ }
+
+ return type;
+ }
+ }
+
+ /**
+ * Returns a URL representation of the file.
+ * @return The URL representation of the file.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public URL getURL() throws FileSystemException
+ {
+ try
+ {
+ return AccessController.doPrivileged(new PrivilegedExceptionAction<URL>()
+ {
+ @Override
+ public URL run() throws MalformedURLException
+ {
+ final StringBuilder buf = new StringBuilder();
+ final String scheme = UriParser.extractScheme(fileName.getURI(), buf);
+ return new URL(scheme, "", -1,
+ buf.toString(), new DefaultURLStreamHandler(fs.getContext(), fs.getFileSystemOptions()));
+ }
+ });
+ }
+ catch (final PrivilegedActionException e)
+ {
+ throw new FileSystemException("vfs.provider/get-url.error", fileName, e.getException());
+ }
+ }
+
+ /**
+ * Called when this file is changed.
+ * <p>
+ * This will only happen if you monitor the file using {@link org.apache.commons.vfs2.FileMonitor}.
+ *
+ * @throws Exception if an error occurs.
+ */
+ protected void handleChanged() throws Exception
+ {
+ // Notify the file system
+ fs.fireFileChanged(this);
+ }
+
+ /**
+ * Called when this file is created. Updates cached info and notifies
+ * the parent and file system.
+ *
+ * @param newType The type of the file.
+ * @throws Exception if an error occurs.
+ */
+ protected void handleCreate(final FileType newType) throws Exception
+ {
+ synchronized (fs)
+ {
+ if (attached)
+ {
+ // Fix up state
+ injectType(newType);
+
+ removeChildrenCache();
+
+ // Notify subclass
+ onChange();
+ }
+
+ // Notify parent that its child list may no longer be valid
+ notifyParent(this.getName(), newType);
+
+ // Notify the file system
+ fs.fireFileCreated(this);
+ }
+ }
+
+ /**
+ * Called when this file is deleted. Updates cached info and notifies
+ * subclasses, parent and file system.
+ * @throws Exception if an error occurs.
+ */
+ protected void handleDelete() throws Exception
+ {
+ synchronized (fs)
+ {
+ if (attached)
+ {
+ // Fix up state
+ injectType(FileType.IMAGINARY);
+ removeChildrenCache();
+
+ // Notify subclass
+ onChange();
+ }
+
+ // Notify parent that its child list may no longer be valid
+ notifyParent(this.getName(), FileType.IMAGINARY);
+
+ // Notify the file system
+ fs.fireFileDeleted(this);
+ }
+ }
+
+ /**
+ * This method is meant to add an object where this object holds a strong reference then.
+ * E.g. a archive-filesystem creates a list of all children and they shouldn't get
+ * garbage collected until the container is garbage collected
+ *
+ * @param strongRef The Object to add.
+ */
+ // TODO should this be a FileObject?
+ public void holdObject(final Object strongRef)
+ {
+ if (objects == null)
+ {
+ objects = new ArrayList<Object>(INITIAL_LIST_SIZE);
+ }
+ objects.add(strongRef);
+ }
+
+ protected void injectType(final FileType fileType)
+ {
+ setFileType(fileType);
+ }
+
+ /**
+ * Check if the internal state is "attached".
+ *
+ * @return true if this is the case
+ */
+ @Override
+ public boolean isAttached()
+ {
+ return attached;
+ }
+
+ /**
+ * Check if the content stream is open.
+ *
+ * @return true if this is the case
+ */
+ @Override
+ public boolean isContentOpen()
+ {
+ if (content == null)
+ {
+ return false;
+ }
+
+ return content.isOpen();
+ }
+
+ /**
+ * Determines if this file is executable.
+ *
+ * @return {@code true} if this file is executable, {@code false} if not.
+ * @throws FileSystemException On error determining if this file exists.
+ */
+ @Override
+ public boolean isExecutable() throws FileSystemException
+ {
+ try
+ {
+ return exists() ? doIsExecutable() : false;
+ }
+ catch (final Exception exc)
+ {
+ throw new FileSystemException("vfs.provider/check-is-executable.error", fileName, exc);
+ }
+ }
+
+ /**
+ * Checks if this file is a regular file by using its file type.
+ *
+ * @return true if this file is a regular file.
+ * @throws FileSystemException if an error occurs.
+ * @see #getType()
+ * @see FileType#FILE
+ */
+ @Override
+ public boolean isFile() throws FileSystemException
+ {
+ // Use equals instead of == to avoid any class loader worries.
+ return FileType.FILE.equals(this.getType());
+ }
+
+ /**
+ * Checks if this file is a folder by using its file type.
+ *
+ * @return true if this file is a regular file.
+ * @throws FileSystemException if an error occurs.
+ * @see #getType()
+ * @see FileType#FOLDER
+ */
+ @Override
+ public boolean isFolder() throws FileSystemException
+ {
+ // Use equals instead of == to avoid any class loader worries.
+ return FileType.FOLDER.equals(this.getType());
+ }
+
+ /**
+ * Determines if this file can be read.
+ * @return true if the file is a hidden file, false otherwise.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public boolean isHidden() throws FileSystemException
+ {
+ try
+ {
+ return exists() ? doIsHidden() : false;
+ }
+ catch (final Exception exc)
+ {
+ throw new FileSystemException("vfs.provider/check-is-hidden.error", fileName, exc);
+ }
+ }
+
+ /**
+ * Determines if this file can be read.
+ * @return true if the file can be read, false otherwise.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public boolean isReadable() throws FileSystemException
+ {
+ try
+ {
+ return exists() ? doIsReadable() : false;
+ }
+ catch (final Exception exc)
+ {
+ throw new FileSystemException("vfs.provider/check-is-readable.error", fileName, exc);
+ }
+ }
+
+ /**
+ * Checks if this fileObject is the same file as {@code destFile} just with a different
+ * name. E.g. for case insensitive filesystems like windows.
+ *
+ * @param destFile The file to compare to.
+ * @return true if the FileObjects are the same.
+ * @throws FileSystemException if an error occurs.
+ */
+ protected boolean isSameFile(final FileObject destFile) throws FileSystemException
+ {
+ attach();
+ return doIsSameFile(destFile);
+ }
+
+ /**
+ * Determines if this file can be written to.
+ * @return true if the file can be written to, false otherwise.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public boolean isWriteable() throws FileSystemException
+ {
+ try
+ {
+ if (exists())
+ {
+ return doIsWriteable();
+ }
+ else
+ {
+ final FileObject parent = getParent();
+ if (parent != null)
+ {
+ return parent.isWriteable();
+ }
+ return true;
+ }
+ }
+ catch (final Exception exc)
+ {
+ throw new FileSystemException("vfs.provider/check-is-writeable.error", fileName, exc);
+ }
+ }
+
+ /**
+ * Returns an iterator over a set of all FileObject in this file object.
+ *
+ * @return an Iterator.
+ */
+ @Override
+ public Iterator<FileObject> iterator()
+ {
+ try
+ {
+ return listFiles(Selectors.SELECT_ALL).iterator();
+ }
+ catch (final FileSystemException e)
+ {
+ throw new IllegalStateException(e);
+ }
+ }
+
+ /**
+ * Lists the set of matching descendants of this file, in depthwise
+ * order.
+ *
+ * @param selector The FileSelector.
+ * @return list of files or null if the base file (this object) do not exist or the {@code selector} is null
+ * @throws FileSystemException if an error occurs.
+ */
+ public List<FileObject> listFiles(final FileSelector selector) throws FileSystemException
+ {
+ if (!exists() || selector == null)
+ {
+ return null;
+ }
+
+ final ArrayList<FileObject> list = new ArrayList<FileObject>();
+ this.findFiles(selector, true, list);
+ return list;
+ }
+
+ /**
+ * Moves (rename) the file to another one.
+ * @param destFile The target FileObject.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public void moveTo(final FileObject destFile) throws FileSystemException
+ {
+ if (canRenameTo(destFile))
+ {
+ if (!getParent().isWriteable())
+ {
+ throw new FileSystemException("vfs.provider/rename-parent-read-only.error",
+ getName(),
+ getParent().getName());
+ }
+ }
+ else
+ {
+ if (!isWriteable())
+ {
+ throw new FileSystemException("vfs.provider/rename-read-only.error", getName());
+ }
+ }
+
+ if (destFile.exists() && !isSameFile(destFile))
+ {
+ destFile.deleteAll();
+ // throw new FileSystemException("vfs.provider/rename-dest-exists.error", destFile.getName());
+ }
+
+ if (canRenameTo(destFile))
+ {
+ // issue rename on same filesystem
+ try
+ {
+ attach();
+ // remember type to avoid attach
+ FileType srcType = getType();
+
+ doRename(destFile);
+
+ FileObjectUtils.getAbstractFileObject(destFile).handleCreate(srcType);
+ destFile.close(); // now the destFile is no longer imaginary. force reattach.
+
+ handleDelete(); // fire delete-events. This file-object (src) is like deleted.
+ }
+ catch (final RuntimeException re)
+ {
+ throw re;
+ }
+ catch (final Exception exc)
+ {
+ throw new FileSystemException("vfs.provider/rename.error", exc,
+ getName(),
+ destFile.getName());
+ }
+ }
+ else
+ {
+ // different fs - do the copy/delete stuff
+
+ destFile.copyFrom(this, Selectors.SELECT_SELF);
+
+ if ((destFile.getType().hasContent()
+ && destFile.getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FILE)
+ || destFile.getType().hasChildren()
+ && destFile.getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FOLDER))
+ && fs.hasCapability(Capability.GET_LAST_MODIFIED))
+ {
+ destFile.getContent().setLastModifiedTime(this.getContent().getLastModifiedTime());
+ }
+
+ deleteSelf();
+ }
+
+ }
+
+ /**
+ * will be called after this file-object closed all its streams.
+ */
+ protected void notifyAllStreamsClosed()
+ {
+ }
+
+ /**
+ * Notify the parent of a change to its children, when a child is created
+ * or deleted.
+ * @param childName The name of the child.
+ * @param newType The type of the child.
+ * @throws Exception if an error occurs.
+ */
+ private void notifyParent(final FileName childName, final FileType newType) throws Exception
+ {
+ if (parent == null)
+ {
+ final FileName parentName = fileName.getParent();
+ if (parentName != null)
+ {
+ // Locate the parent, if it is cached
+ parent = fs.getFileFromCache(parentName);
+ }
+ }
+
+ if (parent != null)
+ {
+ FileObjectUtils.getAbstractFileObject(parent).childrenChanged(childName, newType);
+ }
+ }
+
+ /**
+ * Called when the type or content of this file changes.
+ * <p>
+ * This implementation does nothing.
+ *
+ * @throws Exception if an error occurs.
+ */
+ protected void onChange() throws Exception
+ {
+ }
+
+ /**
+ * Called when the children of this file change. Allows subclasses to
+ * refresh any cached information about the children of this file.
+ * <p>
+ * This implementation does nothing.
+ *
+ * @param child The name of the child that changed.
+ * @param newType The type of the file.
+ * @throws Exception if an error occurs.
+ */
+ protected void onChildrenChanged(final FileName child, final FileType newType) throws Exception
+ {
+ }
+
+ /**
+ * This will prepare the fileObject to get resynchronized with the underlying filesystem if required.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public void refresh() throws FileSystemException
+ {
+ // Detach from the file
+ try
+ {
+ detach();
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("vfs.provider/resync.error", fileName, e);
+ }
+ }
+
+ private void removeChildrenCache()
+ {
+ children = null;
+ }
+
+ private FileObject resolveFile(final FileName child) throws FileSystemException
+ {
+ return fs.resolveFile(child);
+ }
+
+ /**
+ * Finds a file, relative to this file.
+ *
+ * @param path The path of the file to locate. Can either be a relative
+ * path, which is resolved relative to this file, or an
+ * absolute path, which is resolved relative to the file system
+ * that contains this file.
+ * @return The FileObject.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileObject resolveFile(final String path) throws FileSystemException
+ {
+ final FileName otherName = fs.getFileSystemManager().resolveName(fileName, path);
+ return fs.resolveFile(otherName);
+ }
+
+ /**
+ * Returns a child by name.
+ * @param name The name of the child to locate.
+ * @param scope the NameScope.
+ * @return The FileObject for the file or null if the child does not exist.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileObject resolveFile(final String name, final NameScope scope)
+ throws FileSystemException
+ {
+ // return fs.resolveFile(this.name.resolveName(name, scope));
+ return fs.resolveFile(fs.getFileSystemManager().resolveName(this.fileName, name, scope));
+ }
+
+ private FileObject[] resolveFiles(final FileName[] children) throws FileSystemException
+ {
+ if (children == null)
+ {
+ return null;
+ }
+
+ final FileObject[] objects = new FileObject[children.length];
+ for (int iterChildren = 0; iterChildren < children.length; iterChildren++)
+ {
+ objects[iterChildren] = resolveFile(children[iterChildren]);
+ }
+
+ return objects;
+ }
+
+ @Override
+ public boolean setExecutable(final boolean readable, final boolean ownerOnly) throws FileSystemException
+ {
+ try
+ {
+ return exists() ? doSetExecutable(readable, ownerOnly) : false;
+ }
+ catch (final Exception exc)
+ {
+ throw new FileSystemException("vfs.provider/set-executable.error", fileName, exc);
+ }
+ }
+
+ private void setFileType(final FileType type)
+ {
+ if (type != null && type != FileType.IMAGINARY)
+ {
+ try
+ {
+ fileName.setType(type);
+ }
+ catch (final FileSystemException e)
+ {
+ throw new RuntimeException(e.getMessage());
+ }
+ }
+ this.type = type;
+ }
+
+ @Override
+ public boolean setReadable(final boolean readable, final boolean ownerOnly) throws FileSystemException
+ {
+ try
+ {
+ return exists() ? doSetReadable(readable, ownerOnly) : false;
+ }
+ catch (final Exception exc)
+ {
+ throw new FileSystemException("vfs.provider/set-readable.error", fileName, exc);
+ }
+ }
+
+ // --- OPERATIONS ---
+
+ @Override
+ public boolean setWritable(final boolean readable, final boolean ownerOnly) throws FileSystemException
+ {
+ try
+ {
+ return exists() ? doSetWritable(readable, ownerOnly) : false;
+ }
+ catch (final Exception exc)
+ {
+ throw new FileSystemException("vfs.provider/set-writeable.error", fileName, exc);
+ }
+ }
+
+ /**
+ * Returns the URI as a String.
+ *
+ * @return Returns the URI as a String.
+ */
+ @Override
+ public String toString()
+ {
+ return fileName.getURI();
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractFileProvider.java
new file mode 100644
index 0000000..dfd5597
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractFileProvider.java
@@ -0,0 +1,207 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import java.util.Map;
+import java.util.TreeMap;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemConfigBuilder;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.local.GenericFileNameParser;
+
+/**
+ * A partial {@link FileProvider} implementation. Takes care of managing the
+ * file systems created by the provider.
+ */
+public abstract class AbstractFileProvider
+ extends AbstractVfsContainer
+ implements FileProvider
+{
+ private static final AbstractFileSystem[] EMPTY_ABSTRACTFILESYSTEMS = new AbstractFileSystem[0];
+
+ /**
+ * The cached file systems.
+ * <p>
+ * This is a mapping from {@link FileSystemKey} (root URI and options)
+ * to {@link FileSystem}.
+ */
+ private final Map<FileSystemKey, FileSystem> fileSystems
+ = new TreeMap<FileSystemKey, FileSystem>(); // @GuardedBy("self")
+
+ private FileNameParser parser;
+
+ public AbstractFileProvider()
+ {
+ parser = GenericFileNameParser.getInstance();
+ }
+
+ protected FileNameParser getFileNameParser()
+ {
+ return parser;
+ }
+
+ protected void setFileNameParser(final FileNameParser parser)
+ {
+ this.parser = parser;
+ }
+
+ /**
+ * Closes the file systems created by this provider.
+ */
+ @Override
+ public void close()
+ {
+ synchronized (fileSystems)
+ {
+ fileSystems.clear();
+ }
+
+ super.close();
+ }
+
+ /**
+ * Creates a layered file system. This method throws a 'not supported' exception.
+ * @param scheme The protocol to use to access the file.
+ * @param file a FileObject.
+ * @param properties Options to the file system.
+ * @return A FileObject associated with the new FileSystem.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileObject createFileSystem(final String scheme, final FileObject file, final FileSystemOptions properties)
+ throws FileSystemException
+ {
+ // Can't create a layered file system
+ throw new FileSystemException("vfs.provider/not-layered-fs.error", scheme);
+ }
+
+ /**
+ * Adds a file system to those cached by this provider.
+ * <p>
+ * The file system may implement {@link VfsComponent}, in which case it is initialised.
+ * @param key The root file of the file system, part of the cache key.
+ * @param fs the file system to add.
+ * @throws FileSystemException if any error occurs.
+ */
+ protected void addFileSystem(final Comparable<?> key, final FileSystem fs)
+ throws FileSystemException
+ {
+ // Add to the container and initialize
+ addComponent(fs);
+
+ final FileSystemKey treeKey = new FileSystemKey(key, fs.getFileSystemOptions());
+ ((AbstractFileSystem) fs).setCacheKey(treeKey);
+
+ synchronized (fileSystems)
+ {
+ fileSystems.put(treeKey, fs);
+ }
+ }
+
+ /**
+ * Locates a cached file system.
+ *
+ * @param key The root file of the file system, part of the cache key.
+ * @param fileSystemProps file system options the file system instance must have.
+ * @return The file system instance, or null if it is not cached.
+ */
+ protected FileSystem findFileSystem(final Comparable<?> key, final FileSystemOptions fileSystemProps)
+ {
+ final FileSystemKey treeKey = new FileSystemKey(key, fileSystemProps);
+
+ synchronized (fileSystems)
+ {
+ return fileSystems.get(treeKey);
+ }
+ }
+
+ /**
+ * Returns the FileSystemConfigBuidler.
+ * @return the FileSystemConfigBuilder.
+ */
+ @Override
+ public FileSystemConfigBuilder getConfigBuilder()
+ {
+ return null;
+ }
+
+ /**
+ * Free unused resources.
+ */
+ public void freeUnusedResources()
+ {
+ AbstractFileSystem[] abstractFileSystems;
+ synchronized (fileSystems)
+ {
+ // create snapshot under lock
+ abstractFileSystems = fileSystems.values().toArray(EMPTY_ABSTRACTFILESYSTEMS);
+ }
+
+ // process snapshot outside lock
+ for (final AbstractFileSystem fs : abstractFileSystems)
+ {
+ if (fs.isReleaseable())
+ {
+ fs.closeCommunicationLink();
+ }
+ }
+ }
+
+ /**
+ * Close the FileSystem.
+ * @param filesystem The FileSystem to close.
+ */
+ public void closeFileSystem(final FileSystem filesystem)
+ {
+ final AbstractFileSystem fs = (AbstractFileSystem) filesystem;
+
+ final FileSystemKey key = fs.getCacheKey();
+ if (key != null)
+ {
+ synchronized (fileSystems)
+ {
+ fileSystems.remove(key);
+ }
+ }
+
+ removeComponent(fs);
+ fs.close();
+ }
+
+ /**
+ * Parses an absolute URI.
+ *
+ * @param base The base file - if null the {@code uri} needs to be absolute
+ * @param uri The URI to parse.
+ * @return The FileName.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileName parseUri(final FileName base, final String uri) throws FileSystemException
+ {
+ if (getFileNameParser() != null)
+ {
+ return getFileNameParser().parseUri(getContext(), base, uri);
+ }
+
+ throw new FileSystemException("vfs.provider/filename-parser-missing.error");
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractFileSystem.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractFileSystem.java
new file mode 100644
index 0000000..b46bcf8
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractFileSystem.java
@@ -0,0 +1,683 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import java.io.File;
+import java.lang.reflect.InvocationTargetException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.atomic.AtomicLong;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.vfs2.CacheStrategy;
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileListener;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSelector;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemConfigBuilder;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.FilesCache;
+import org.apache.commons.vfs2.VfsLog;
+import org.apache.commons.vfs2.cache.OnCallRefreshFileObject;
+import org.apache.commons.vfs2.events.AbstractFileChangeEvent;
+import org.apache.commons.vfs2.events.ChangedEvent;
+import org.apache.commons.vfs2.events.CreateEvent;
+import org.apache.commons.vfs2.events.DeleteEvent;
+import org.apache.commons.vfs2.impl.DefaultFileSystemConfigBuilder;
+import org.apache.commons.vfs2.util.Messages;
+
+/**
+ * A partial {@link org.apache.commons.vfs2.FileSystem} implementation.
+ */
+public abstract class AbstractFileSystem
+ extends AbstractVfsComponent
+ implements FileSystem
+{
+ private static final Log LOG = LogFactory.getLog(AbstractFileSystem.class);
+
+ /**
+ * The "root" of the file system. This is always "/" so it isn't always the "real"
+ * root.
+ */
+ private final FileName rootName;
+
+ /**
+ * The root URI of the file system. The base path specified as a file system option
+ * when the file system was created.
+ */
+ private final String rootURI;
+
+ private final Collection<Capability> caps = new HashSet<Capability>();
+
+ private FileObject parentLayer;
+
+ /**
+ * Map from FileName to an ArrayList of listeners for that file.
+ */
+ private final Map<FileName, ArrayList<FileListener>> listenerMap = new HashMap<FileName, ArrayList<FileListener>>();
+
+ /**
+ * FileSystemOptions used for configuration
+ */
+ private final FileSystemOptions fileSystemOptions;
+
+ /**
+ * How many fileObjects are handed out
+ */
+ private final AtomicLong useCount = new AtomicLong(0);
+
+
+ private FileSystemKey cacheKey;
+
+ /**
+ * open streams counter for this filesystem
+ */
+ private final AtomicInteger openStreams = new AtomicInteger(0);
+
+ protected AbstractFileSystem(final FileName rootName,
+ final FileObject parentLayer,
+ final FileSystemOptions fileSystemOptions)
+ {
+ this.parentLayer = parentLayer;
+ this.rootName = rootName;
+ this.fileSystemOptions = fileSystemOptions;
+ final FileSystemConfigBuilder builder = DefaultFileSystemConfigBuilder.getInstance();
+ String uri = builder.getRootURI(fileSystemOptions);
+ if (uri == null)
+ {
+ uri = rootName.getURI();
+ }
+ this.rootURI = uri;
+ }
+
+ /**
+ * Initializes this component.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public void init() throws FileSystemException
+ {
+ addCapabilities(caps);
+ }
+
+ /**
+ * Closes this component.
+ */
+ @Override
+ public void close()
+ {
+ closeCommunicationLink();
+
+ parentLayer = null;
+ }
+
+ /**
+ * Close the underlying link used to access the files.
+ */
+ public void closeCommunicationLink()
+ {
+ synchronized (this)
+ {
+ doCloseCommunicationLink();
+ }
+ }
+
+ /**
+ * Close the underlying link used to access the files
+ */
+ protected void doCloseCommunicationLink()
+ {
+ }
+
+ /**
+ * Creates a file object.
+ * <p>
+ * This method is called only if the requested file is not cached.
+ *
+ * @param name name referencing the new file.
+ * @return new created FileObject.
+ * @throws Exception might throw an Exception, which is then wrapped in FileSystemException.
+ */
+ protected abstract FileObject createFile(final AbstractFileName name) throws Exception;
+
+ /**
+ * Adds the capabilities of this file system.
+ *
+ * @param caps collections of Capabilities, can be immutable.
+ */
+ protected abstract void addCapabilities(Collection<Capability> caps);
+
+ /**
+ * Returns the name of the root of this file system.
+ * @return the root FileName.
+ */
+ @Override
+ public FileName getRootName()
+ {
+ return rootName;
+ }
+
+ /**
+ * Returns the root URI specified for this file System.
+ * @return The root URI used in this file system.
+ * @since 2.0
+ */
+ @Override
+ public String getRootURI()
+ {
+ return rootURI;
+ }
+
+ /**
+ * Adds a file object to the cache.
+ * @param file the file to add.
+ */
+ protected void putFileToCache(final FileObject file)
+ {
+ getCache().putFile(file);
+ }
+
+ private FilesCache getCache()
+ {
+ FilesCache files;
+ files = getContext().getFileSystemManager().getFilesCache();
+ if (files == null)
+ {
+ throw new RuntimeException(Messages.getString("vfs.provider/files-cache-missing.error"));
+ }
+
+ return files;
+ }
+
+ /**
+ * Returns a cached file.
+ * @param name name to search for.
+ * @return file object or null if not found.
+ */
+ protected FileObject getFileFromCache(final FileName name)
+ {
+ return getCache().getFile(this, name);
+ }
+
+ /**
+ * Remove a cached file.
+ * @param name The file name to remove.
+ */
+ protected void removeFileFromCache(final FileName name)
+ {
+ getCache().removeFile(this, name);
+ }
+
+ /**
+ * Determines if this file system has a particular capability.
+ * @param capability the Capability to check for.
+ * @return true if the FileSystem has the Capability, false otherwise.
+ */
+ @Override
+ public boolean hasCapability(final Capability capability)
+ {
+ return caps.contains(capability);
+ }
+
+ /**
+ * Retrieves the attribute with the specified name. The default
+ * implementation simply throws an exception.
+ * @param attrName The name of the attribute.
+ * @return the Object associated with the attribute or null if no object is.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public Object getAttribute(final String attrName) throws FileSystemException
+ {
+ throw new FileSystemException("vfs.provider/get-attribute-not-supported.error");
+ }
+
+ /**
+ * Sets the attribute with the specified name. The default
+ * implementation simply throws an exception.
+ * @param attrName the attribute name.
+ * @param value The object to associate with the attribute.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public void setAttribute(final String attrName, final Object value)
+ throws FileSystemException
+ {
+ throw new FileSystemException("vfs.provider/set-attribute-not-supported.error");
+ }
+
+ /**
+ * Returns the parent layer if this is a layered file system.
+ * @return The FileObject for the parent layer.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileObject getParentLayer() throws FileSystemException
+ {
+ return parentLayer;
+ }
+
+ /**
+ * Returns the root file of this file system.
+ * @return The root FileObject of the FileSystem
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileObject getRoot() throws FileSystemException
+ {
+ return resolveFile(rootName);
+ }
+
+ /**
+ * Finds a file in this file system.
+ * @param nameStr The name of the file to resolve.
+ * @return The located FileObject or null if none could be located.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileObject resolveFile(final String nameStr) throws FileSystemException
+ {
+ // Resolve the name, and create the file
+ final FileName name = getFileSystemManager().resolveName(rootName, nameStr);
+ return resolveFile(name);
+ }
+
+ /**
+ * Finds a file in this file system.
+ * @param name The name of the file to locate.
+ * @return The located FileObject or null if none could be located.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileObject resolveFile(final FileName name) throws FileSystemException
+ {
+ return resolveFile(name, true);
+ }
+
+ private synchronized FileObject resolveFile(final FileName name, final boolean useCache) throws FileSystemException
+ {
+ if (!rootName.getRootURI().equals(name.getRootURI()))
+ {
+ throw new FileSystemException("vfs.provider/mismatched-fs-for-name.error",
+ name, rootName, name.getRootURI());
+ }
+
+ // imario@apache.org ==> use getFileFromCache
+ FileObject file;
+ if (useCache)
+ {
+ file = getFileFromCache(name);
+ }
+ else
+ {
+ file = null;
+ }
+
+ if (file == null)
+ {
+ try
+ {
+ file = createFile((AbstractFileName) name);
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("vfs.provider/resolve-file.error", name, e);
+ }
+
+ file = decorateFileObject(file);
+
+ // imario@apache.org ==> use putFileToCache
+ if (useCache)
+ {
+ putFileToCache(file);
+ }
+ }
+
+ /**
+ * resync the file information if requested
+ */
+ if (getFileSystemManager().getCacheStrategy().equals(CacheStrategy.ON_RESOLVE))
+ {
+ file.refresh();
+ }
+ return file;
+ }
+
+ protected FileObject decorateFileObject(FileObject file) throws FileSystemException
+ {
+ if (getFileSystemManager().getCacheStrategy().equals(CacheStrategy.ON_CALL))
+ {
+ file = new OnCallRefreshFileObject(file);
+ }
+
+ if (getFileSystemManager().getFileObjectDecoratorConst() != null)
+ {
+ try
+ {
+ file = (FileObject) getFileSystemManager().getFileObjectDecoratorConst().
+ newInstance(new Object[]{file});
+ }
+ catch (final InstantiationException e)
+ {
+ throw new FileSystemException("vfs.impl/invalid-decorator.error",
+ getFileSystemManager().getFileObjectDecorator().getName(), e);
+ }
+ catch (final IllegalAccessException e)
+ {
+ throw new FileSystemException("vfs.impl/invalid-decorator.error",
+ getFileSystemManager().getFileObjectDecorator().getName(), e);
+ }
+ catch (final InvocationTargetException e)
+ {
+ throw new FileSystemException("vfs.impl/invalid-decorator.error",
+ getFileSystemManager().getFileObjectDecorator().getName(), e);
+ }
+ }
+
+ return file;
+ }
+
+ /**
+ * Creates a temporary local copy of a file and its descendants.
+ * @param file The FileObject to replicate.
+ * @param selector The FileSelector.
+ * @return The replicated File.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public File replicateFile(final FileObject file,
+ final FileSelector selector)
+ throws FileSystemException
+ {
+ if (!file.exists())
+ {
+ throw new FileSystemException("vfs.provider/replicate-missing-file.error", file.getName());
+ }
+
+ try
+ {
+ return doReplicateFile(file, selector);
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("vfs.provider/replicate-file.error", file.getName(), e);
+ }
+ }
+
+ /**
+ * Return the FileSystemOptions used to instantiate this filesystem.
+ * @return the FileSystemOptions.
+ */
+ @Override
+ public FileSystemOptions getFileSystemOptions()
+ {
+ return fileSystemOptions;
+ }
+
+ /**
+ * Return the FileSystemManager used to instantiate this filesystem.
+ * @return the FileSystemManager.
+ */
+ @Override
+ public FileSystemManager getFileSystemManager()
+ {
+ return getContext().getFileSystemManager();
+ }
+
+ /**
+ * Returns the accuracy of the last modification time.
+ *
+ * @return ms 0 perfectly accurate, {@literal >0} might be off by this value e.g. sftp 1000ms
+ */
+ @Override
+ public double getLastModTimeAccuracy()
+ {
+ return 0;
+ }
+
+ /**
+ * Creates a temporary local copy of a file and its descendants.
+ *
+ * @param file the start of the tree.
+ * @param selector selection what to do with childs.
+ * @return replicated root file.
+ * @throws Exception any Exception is wrapped as FileSystemException.
+ */
+ protected File doReplicateFile(final FileObject file,
+ final FileSelector selector)
+ throws Exception
+ {
+ return getContext().getReplicator().replicateFile(file, selector);
+ }
+
+ /**
+ * Adds a junction to this file system.
+ * @param junctionPoint The junction point.
+ * @param targetFile The target to add.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public void addJunction(final String junctionPoint,
+ final FileObject targetFile)
+ throws FileSystemException
+ {
+ throw new FileSystemException("vfs.provider/junctions-not-supported.error", rootName);
+ }
+
+ /**
+ * Removes a junction from this file system.
+ * @param junctionPoint The junction point.
+ * @throws FileSystemException if an error occurs
+ */
+ @Override
+ public void removeJunction(final String junctionPoint) throws FileSystemException
+ {
+ throw new FileSystemException("vfs.provider/junctions-not-supported.error", rootName);
+ }
+
+ /**
+ * Adds a listener on a file in this file system.
+ * @param file The FileObject to be monitored.
+ * @param listener The FileListener
+ */
+ @Override
+ public void addListener(final FileObject file,
+ final FileListener listener)
+ {
+ synchronized (listenerMap)
+ {
+ ArrayList<FileListener> listeners = listenerMap.get(file.getName());
+ if (listeners == null)
+ {
+ listeners = new ArrayList<FileListener>();
+ listenerMap.put(file.getName(), listeners);
+ }
+ listeners.add(listener);
+ }
+ }
+
+ /**
+ * Removes a listener from a file in this file system.
+ * @param file The FileObject to be monitored.
+ * @param listener The FileListener
+ */
+ @Override
+ public void removeListener(final FileObject file,
+ final FileListener listener)
+ {
+ synchronized (listenerMap)
+ {
+ final ArrayList<?> listeners = listenerMap.get(file.getName());
+ if (listeners != null)
+ {
+ listeners.remove(listener);
+ if (listeners.isEmpty())
+ {
+ listenerMap.remove(file.getName());
+ }
+ }
+ }
+ }
+
+ /**
+ * Fires a file create event.
+ * @param file The FileObject that was created.
+ */
+ public void fireFileCreated(final FileObject file)
+ {
+ fireEvent(new CreateEvent(file));
+ }
+
+ /**
+ * Fires a file delete event.
+ * @param file The FileObject that was deleted.
+ */
+ public void fireFileDeleted(final FileObject file)
+ {
+ fireEvent(new DeleteEvent(file));
+ }
+
+ /**
+ * Fires a file changed event.
+ * <p>
+ * This will only happen if you monitor the file using {@link org.apache.commons.vfs2.FileMonitor}.
+ *
+ * @param file The FileObject that changed.
+ */
+ public void fireFileChanged(final FileObject file)
+ {
+ fireEvent(new ChangedEvent(file));
+ }
+
+ /**
+ * Returns true if no file is using this filesystem.
+ *
+ * @return true if no file is using this FileSystem.
+ */
+ public boolean isReleaseable()
+ {
+ return useCount.get() < 1;
+ }
+
+ void freeResources()
+ {
+ }
+
+ /**
+ * Fires an event.
+ */
+ private void fireEvent(final AbstractFileChangeEvent event)
+ {
+ FileListener[] fileListeners = null;
+ final FileObject file = event.getFile();
+
+ synchronized (listenerMap)
+ {
+ final ArrayList<?> listeners = listenerMap.get(file.getName());
+ if (listeners != null)
+ {
+ fileListeners = listeners.toArray(new FileListener[listeners.size()]);
+ }
+ }
+
+ if (fileListeners != null)
+ {
+ for (final FileListener fileListener : fileListeners)
+ {
+ try
+ {
+ event.notify(fileListener);
+ }
+ catch (final Exception e)
+ {
+ final String message = Messages.getString("vfs.provider/notify-listener.warn", file);
+ // getLogger().warn(message, e);
+ VfsLog.warn(getLogger(), LOG, message, e);
+ }
+ }
+ }
+ }
+
+ void fileObjectHanded(final FileObject fileObject)
+ {
+ useCount.incrementAndGet();
+ }
+
+ void fileObjectDestroyed(final FileObject fileObject)
+ {
+ useCount.decrementAndGet();
+ }
+
+ void setCacheKey(final FileSystemKey cacheKey)
+ {
+ this.cacheKey = cacheKey;
+ }
+
+ FileSystemKey getCacheKey()
+ {
+ return this.cacheKey;
+ }
+
+ void streamOpened()
+ {
+ openStreams.incrementAndGet();
+ }
+
+ void streamClosed()
+ {
+ int count;
+
+ do
+ {
+ count = openStreams.get();
+ if (count < 1)
+ {
+ return;
+ }
+ } while(openStreams.compareAndSet(count, count - 1));
+
+ if (count == 1)
+ {
+ notifyAllStreamsClosed();
+ }
+ }
+
+ /**
+ * will be called after all file-objects closed their streams.
+ */
+ protected void notifyAllStreamsClosed()
+ {
+ }
+
+ /**
+ * check if this filesystem has open streams.
+ * @return true if the FileSystem has open streams.
+ */
+ public boolean isOpen()
+ {
+ return openStreams.get() > 0;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractLayeredFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractLayeredFileProvider.java
new file mode 100644
index 0000000..e2bea71
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractLayeredFileProvider.java
@@ -0,0 +1,109 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+
+/**
+ * A {@link FileProvider} that is layered on top of another, such as the
+ * contents of a zip or tar file.
+ */
+public abstract class AbstractLayeredFileProvider
+ extends AbstractFileProvider
+{
+ public AbstractLayeredFileProvider()
+ {
+ super();
+ setFileNameParser(LayeredFileNameParser.getInstance());
+ }
+
+ /**
+ * Locates a file object, by absolute URI.
+ * @param baseFile The base FileObject.
+ * @param uri The name of the file to locate.
+ * @param fileSystemOptions The FileSystemOptions.
+ * @return The FileObject if it is located, null otherwise.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileObject findFile(final FileObject baseFile,
+ final String uri,
+ final FileSystemOptions fileSystemOptions) throws FileSystemException
+ {
+ // Split the URI up into its parts
+ final LayeredFileName name = (LayeredFileName) parseUri(baseFile != null ? baseFile.getName() : null, uri);
+
+ // Make the URI canonical
+
+ // Resolve the outer file name
+ final FileName fileName = name.getOuterName();
+ final FileObject file = getContext().resolveFile(baseFile, fileName.getURI(), fileSystemOptions);
+
+ // Create the file system
+ final FileObject rootFile = createFileSystem(name.getScheme(), file, fileSystemOptions);
+
+ // Resolve the file
+ return rootFile.resolveFile(name.getPath());
+ }
+
+ /**
+ * Creates a layered file system.
+ * @param scheme The protocol to use.
+ * @param file a FileObject.
+ * @param fileSystemOptions Options to access the FileSystem.
+ * @return A FileObject associated with the new FileSystem.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public synchronized FileObject createFileSystem(final String scheme,
+ final FileObject file,
+ final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ // Check if cached
+ final FileName rootName = file.getName();
+ FileSystem fs = findFileSystem(rootName, fileSystemOptions);
+ if (fs == null)
+ {
+ // Create the file system
+ fs = doCreateFileSystem(scheme, file, fileSystemOptions);
+ addFileSystem(rootName, fs);
+ }
+ return fs.getRoot();
+ }
+
+ /**
+ * Creates a layered file system.
+ * <p>
+ * This method is called if the file system is not cached.
+ *
+ * @param scheme The URI scheme.
+ * @param file The file to create the file system on top of.
+ * @param fileSystemOptions options for new and underlying file systems.
+ * @return The file system, never null. Might implement {@link VfsComponent}.
+ * @throws FileSystemException if the file system cannot be created.
+ */
+ protected abstract FileSystem doCreateFileSystem(final String scheme,
+ final FileObject file,
+ final FileSystemOptions fileSystemOptions)
+ throws FileSystemException;
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractOriginatingFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractOriginatingFileProvider.java
new file mode 100644
index 0000000..216641b
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractOriginatingFileProvider.java
@@ -0,0 +1,121 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+
+/**
+ * A {@link FileProvider} that handles physical files, such as the files in a
+ * local fs, or on an FTP server. An originating file system cannot be
+ * layered on top of another file system.
+ */
+public abstract class AbstractOriginatingFileProvider
+ extends AbstractFileProvider
+{
+ public AbstractOriginatingFileProvider()
+ {
+ super();
+ }
+
+ /**
+ * Locates a file object, by absolute URI.
+ *
+ * @param baseFile The base file object.
+ * @param uri The URI of the file to locate
+ * @param fileSystemOptions The FileSystem options.
+ * @return The located FileObject
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileObject findFile(final FileObject baseFile,
+ final String uri,
+ final FileSystemOptions fileSystemOptions) throws FileSystemException
+ {
+ // Parse the URI
+ final FileName name;
+ try
+ {
+ name = parseUri(baseFile != null ? baseFile.getName() : null, uri);
+ }
+ catch (final FileSystemException exc)
+ {
+ throw new FileSystemException("vfs.provider/invalid-absolute-uri.error", uri, exc);
+ }
+
+ // Locate the file
+ return findFile(name, fileSystemOptions);
+ }
+
+ /**
+ * Locates a file from its parsed URI.
+ * @param name The file name.
+ * @param fileSystemOptions FileSystem options.
+ * @return A FileObject associated with the file.
+ * @throws FileSystemException if an error occurs.
+ */
+ protected FileObject findFile(final FileName name, final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ // Check in the cache for the file system
+ final FileName rootName = getContext().getFileSystemManager().resolveName(name, FileName.ROOT_PATH);
+
+ final FileSystem fs = getFileSystem(rootName, fileSystemOptions);
+
+ // Locate the file
+ // return fs.resolveFile(name.getPath());
+ return fs.resolveFile(name);
+ }
+
+ /**
+ * Returns the FileSystem associated with the specified root.
+ * @param rootName The root path.
+ * @param fileSystemOptions The FileSystem options.
+ * @return The FileSystem.
+ * @throws FileSystemException if an error occurs.
+ * @since 2.0
+ */
+ protected synchronized FileSystem getFileSystem(final FileName rootName, final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ FileSystem fs = findFileSystem(rootName, fileSystemOptions);
+ if (fs == null)
+ {
+ // Need to create the file system, and cache it
+ fs = doCreateFileSystem(rootName, fileSystemOptions);
+ addFileSystem(rootName, fs);
+ }
+ return fs;
+ }
+
+
+
+ /**
+ * Creates a {@link FileSystem}. If the returned FileSystem implements
+ * {@link VfsComponent}, it will be initialised.
+ *
+ * @param rootName The name of the root file of the file system to create.
+ * @param fileSystemOptions The FileSystem options.
+ * @return The FileSystem.
+ * @throws FileSystemException if an error occurs.
+ */
+ protected abstract FileSystem doCreateFileSystem(final FileName rootName, final FileSystemOptions fileSystemOptions)
+ throws FileSystemException;
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractRandomAccessContent.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractRandomAccessContent.java
new file mode 100644
index 0000000..1da7477
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractRandomAccessContent.java
@@ -0,0 +1,132 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import java.io.IOException;
+
+import org.apache.commons.vfs2.RandomAccessContent;
+import org.apache.commons.vfs2.util.RandomAccessMode;
+
+/**
+ * Implements the {@link java.io.DataOutput} part of the {@link RandomAccessContent} interface and throws
+ * {@link UnsupportedOperationException} when one of these methods are called. For read-only random access
+ * implementations.
+ */
+public abstract class AbstractRandomAccessContent implements RandomAccessContent
+{
+ protected AbstractRandomAccessContent(final RandomAccessMode mode)
+ {
+ }
+
+ /**
+ * @deprecated see {@link java.io.DataInputStream#readLine()} This method will be removed when it is removed from
+ * the DataInput interface this class implements (which will probably never happen).
+ * @return The line as a String.
+ * @throws IOException
+ * if an error occurs.
+ */
+ @Override
+ @Deprecated
+ public String readLine() throws IOException
+ {
+ throw new UnsupportedOperationException("deprecated");
+ }
+
+ @Override
+ public void write(final byte[] b) throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void write(final byte[] b, final int off, final int len) throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void write(final int b) throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void writeBoolean(final boolean v) throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void writeByte(final int v) throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void writeBytes(final String s) throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void writeChar(final int v) throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void writeChars(final String s) throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void writeDouble(final double v) throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void writeFloat(final float v) throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void writeInt(final int v) throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void writeLong(final long v) throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void writeShort(final int v) throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ @Override
+ public void writeUTF(final String str) throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractRandomAccessStreamContent.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractRandomAccessStreamContent.java
new file mode 100644
index 0000000..db1fd25
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractRandomAccessStreamContent.java
@@ -0,0 +1,132 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import java.io.DataInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.apache.commons.vfs2.util.RandomAccessMode;
+
+/**
+ * Implements the part usable for all stream-based random access.
+ */
+public abstract class AbstractRandomAccessStreamContent extends AbstractRandomAccessContent
+{
+ protected AbstractRandomAccessStreamContent(final RandomAccessMode mode)
+ {
+ super(mode);
+ }
+
+ protected abstract DataInputStream getDataInputStream() throws IOException;
+
+ @Override
+ public byte readByte() throws IOException
+ {
+ return getDataInputStream().readByte();
+ }
+
+ @Override
+ public char readChar() throws IOException
+ {
+ return getDataInputStream().readChar();
+ }
+
+ @Override
+ public double readDouble() throws IOException
+ {
+ return getDataInputStream().readDouble();
+ }
+
+ @Override
+ public float readFloat() throws IOException
+ {
+ return getDataInputStream().readFloat();
+ }
+
+ @Override
+ public int readInt() throws IOException
+ {
+ return getDataInputStream().readInt();
+ }
+
+ @Override
+ public int readUnsignedByte() throws IOException
+ {
+ return getDataInputStream().readUnsignedByte();
+ }
+
+ @Override
+ public int readUnsignedShort() throws IOException
+ {
+ return getDataInputStream().readUnsignedShort();
+ }
+
+ @Override
+ public long readLong() throws IOException
+ {
+ return getDataInputStream().readLong();
+ }
+
+ @Override
+ public short readShort() throws IOException
+ {
+ return getDataInputStream().readShort();
+ }
+
+ @Override
+ public boolean readBoolean() throws IOException
+ {
+ return getDataInputStream().readBoolean();
+ }
+
+ @Override
+ public int skipBytes(final int n) throws IOException
+ {
+ return getDataInputStream().skipBytes(n);
+ }
+
+ @Override
+ public void readFully(final byte[] b) throws IOException
+ {
+ getDataInputStream().readFully(b);
+ }
+
+ @Override
+ public void readFully(final byte[] b, final int off, final int len) throws IOException
+ {
+ getDataInputStream().readFully(b, off, len);
+ }
+
+ @Override
+ public String readUTF() throws IOException
+ {
+ return getDataInputStream().readUTF();
+ }
+
+ @Override
+ public InputStream getInputStream() throws IOException
+ {
+ return getDataInputStream();
+ }
+
+ @Override
+ public void setLength(final long newLength) throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractVfsComponent.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractVfsComponent.java
new file mode 100644
index 0000000..4311aff
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractVfsComponent.java
@@ -0,0 +1,85 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.vfs2.FileSystemException;
+
+/**
+ * A partial {@link VfsComponent} implementation.
+ */
+public abstract class AbstractVfsComponent
+ implements VfsComponent
+{
+ private VfsComponentContext context;
+ private Log log;
+
+ /**
+ * Sets the Logger to use for the component.
+ * @param log The Log to use.
+ */
+ @Override
+ public final void setLogger(final Log log)
+ {
+ this.log = log;
+ }
+
+ /**
+ * Sets the context for this file system provider.
+ * @param context The VfsComponentContext.
+ */
+ @Override
+ public final void setContext(final VfsComponentContext context)
+ {
+ this.context = context;
+ }
+
+ /**
+ * Initializes the component. This implementation does nothing.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public void init() throws FileSystemException
+ {
+ }
+
+ /**
+ * Closes the provider. This implementation does nothing.
+ */
+ @Override
+ public void close()
+ {
+ }
+
+ /**
+ * Returns the logger for this file system to use.
+ * @return logger for this file system
+ */
+ protected final Log getLogger()
+ {
+ return log;
+ }
+
+ /**
+ * Returns the context for this provider.
+ * @return provider context
+ */
+ protected final VfsComponentContext getContext()
+ {
+ return context;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractVfsContainer.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractVfsContainer.java
new file mode 100644
index 0000000..1156709
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/AbstractVfsContainer.java
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import java.util.ArrayList;
+
+import org.apache.commons.vfs2.FileSystemException;
+
+/**
+ * A {@link VfsComponent} that contains a set of sub-components.
+ */
+public abstract class AbstractVfsContainer
+ extends AbstractVfsComponent
+{
+ /**
+ * The components contained by this component.
+ */
+ private final ArrayList<Object> components
+ = new ArrayList<Object>(); // @GuardedBy("self")
+
+ /**
+ * Adds a sub-component to this component.
+ * <p>
+ * If the sub-component implements {@link VfsComponent}, it is initialised.
+ * All sub-components are closed when this component is closed.
+ * @param component the component to add.
+ * @throws FileSystemException if any error occurs.
+ */
+ protected void addComponent(final Object component)
+ throws FileSystemException
+ {
+ synchronized (components)
+ {
+ if (!components.contains(component))
+ {
+ // Initialise
+ if (component instanceof VfsComponent)
+ {
+ final VfsComponent vfsComponent = (VfsComponent) component;
+ vfsComponent.setLogger(getLogger());
+ vfsComponent.setContext(getContext());
+ vfsComponent.init();
+ }
+
+ // Keep track of component, to close it later
+ components.add(component);
+ }
+ } // synchronized
+ }
+
+ /**
+ * Removes a sub-component from this component.
+ *
+ * @param component the component to remove.
+ */
+ protected void removeComponent(final Object component)
+ {
+ synchronized (components)
+ {
+ // multiple instances should not happen
+ components.remove(component);
+ }
+ }
+
+ /**
+ * Closes the sub-components of this component.
+ */
+ @Override
+ public void close()
+ {
+ final Object[] toclose;
+ synchronized (components)
+ {
+ toclose = components.toArray();
+ components.clear();
+ }
+
+ // Close all components
+ for (Object component : toclose)
+ {
+ if (component instanceof VfsComponent)
+ {
+ final VfsComponent vfsComponent = (VfsComponent) component;
+ vfsComponent.close();
+ }
+ }
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/CompositeFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/CompositeFileProvider.java
new file mode 100644
index 0000000..9eb2bfb
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/CompositeFileProvider.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+
+/**
+ * Description.
+ */
+public abstract class CompositeFileProvider extends AbstractFileProvider
+{
+ private static final int INITIAL_BUFSZ = 80;
+
+ public CompositeFileProvider()
+ {
+ super();
+ }
+
+ /**
+ * The schemes known.
+ * @return Array of supported schemes.
+ */
+ protected abstract String[] getSchemes();
+
+ /**
+ * Locates a file object, by absolute URI.
+ * @param baseFile The base FileObject.
+ * @param uri The file to find.
+ * @param fileSystemOptions The options for the FileSystem.
+ * @return A FileObject for the located file.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileObject findFile(final FileObject baseFile,
+ final String uri,
+ final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ final StringBuilder buf = new StringBuilder(INITIAL_BUFSZ);
+
+ UriParser.extractScheme(uri, buf);
+
+ final String[] schemes = getSchemes();
+ for (final String scheme : schemes)
+ {
+ buf.insert(0, ":");
+ buf.insert(0, scheme);
+ }
+
+ final FileObject fo = getContext().getFileSystemManager().resolveFile(buf.toString(), fileSystemOptions);
+ return fo;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/DefaultFileContent.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/DefaultFileContent.java
new file mode 100644
index 0000000..11aab2e
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/DefaultFileContent.java
@@ -0,0 +1,902 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.security.cert.Certificate;
+import java.util.Collections;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.commons.vfs2.FileContent;
+import org.apache.commons.vfs2.FileContentInfo;
+import org.apache.commons.vfs2.FileContentInfoFactory;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.RandomAccessContent;
+import org.apache.commons.vfs2.util.MonitorInputStream;
+import org.apache.commons.vfs2.util.MonitorOutputStream;
+import org.apache.commons.vfs2.util.MonitorRandomAccessContent;
+import org.apache.commons.vfs2.util.RandomAccessMode;
+
+/**
+ * The content of a file.
+ */
+public final class DefaultFileContent implements FileContent
+{
+ /*
+ static final int STATE_NONE = 0;
+ static final int STATE_READING = 1;
+ static final int STATE_WRITING = 2;
+ static final int STATE_RANDOM_ACCESS = 3;
+ */
+
+ static final int STATE_CLOSED = 0;
+ static final int STATE_OPENED = 1;
+
+ /**
+ * The default buffer size for {@link #write(OutputStream)}
+ */
+ private static final int WRITE_BUFFER_SIZE = 4096;
+
+ private final AbstractFileObject fileObject;
+ private Map<String, Object> attrs;
+ private Map<String, Object> roAttrs;
+ private FileContentInfo fileContentInfo;
+ private final FileContentInfoFactory fileContentInfoFactory;
+
+ private final ThreadLocal<FileContentThreadData> threadData = new ThreadLocal<FileContentThreadData>();
+ private boolean resetAttributes;
+
+ /**
+ * open streams counter for this file
+ */
+ private int openStreams;
+
+ public DefaultFileContent(final AbstractFileObject file, final FileContentInfoFactory fileContentInfoFactory)
+ {
+ this.fileObject = file;
+ this.fileContentInfoFactory = fileContentInfoFactory;
+ }
+
+ private FileContentThreadData getOrCreateThreadData()
+ {
+ FileContentThreadData data = this.threadData.get();
+ if (data == null)
+ {
+ data = new FileContentThreadData();
+ this.threadData.set(data);
+ }
+ return data;
+ }
+
+ void streamOpened()
+ {
+ synchronized (this)
+ {
+ openStreams++;
+ }
+ ((AbstractFileSystem) fileObject.getFileSystem()).streamOpened();
+ }
+
+ void streamClosed()
+ {
+ synchronized (this)
+ {
+ if (openStreams > 0)
+ {
+ openStreams--;
+ if (openStreams < 1)
+ {
+ fileObject.notifyAllStreamsClosed();
+ }
+ }
+ }
+ ((AbstractFileSystem) fileObject.getFileSystem()).streamClosed();
+ }
+
+ /**
+ * Returns the file that this is the content of.
+ * @return the FileObject.
+ */
+ @Override
+ public FileObject getFile()
+ {
+ return fileObject;
+ }
+
+ /**
+ * Returns the size of the content (in bytes).
+ * @return The size of the content (in bytes).
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public long getSize() throws FileSystemException
+ {
+ // Do some checking
+ if (!fileObject.getType().hasContent())
+ {
+ throw new FileSystemException("vfs.provider/get-size-not-file.error", fileObject);
+ }
+ /*
+ if (getThreadData().getState() == STATE_WRITING || getThreadData().getState() == STATE_RANDOM_ACCESS)
+ {
+ throw new FileSystemException("vfs.provider/get-size-write.error", file);
+ }
+ */
+
+ try
+ {
+ // Get the size
+ return fileObject.doGetContentSize();
+ }
+ catch (final Exception exc)
+ {
+ throw new FileSystemException("vfs.provider/get-size.error", exc, fileObject);
+ }
+ }
+
+ /**
+ * Returns the last-modified timestamp.
+ * @return The last modified timestamp.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public long getLastModifiedTime() throws FileSystemException
+ {
+ /*
+ if (getThreadData().getState() == STATE_WRITING || getThreadData().getState() == STATE_RANDOM_ACCESS)
+ {
+ throw new FileSystemException("vfs.provider/get-last-modified-writing.error", file);
+ }
+ */
+ if (!fileObject.getType().hasAttributes())
+ {
+ throw new FileSystemException("vfs.provider/get-last-modified-no-exist.error", fileObject);
+ }
+ try
+ {
+ return fileObject.doGetLastModifiedTime();
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("vfs.provider/get-last-modified.error", fileObject, e);
+ }
+ }
+
+ /**
+ * Sets the last-modified timestamp.
+ * @param modTime The last modified timestamp.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public void setLastModifiedTime(final long modTime) throws FileSystemException
+ {
+ /*
+ if (getThreadData().getState() == STATE_WRITING || getThreadData().getState() == STATE_RANDOM_ACCESS)
+ {
+ throw new FileSystemException("vfs.provider/set-last-modified-writing.error", file);
+ }
+ */
+ if (!fileObject.getType().hasAttributes())
+ {
+ throw new FileSystemException("vfs.provider/set-last-modified-no-exist.error", fileObject);
+ }
+ try
+ {
+ if (!fileObject.doSetLastModifiedTime(modTime))
+ {
+ throw new FileSystemException("vfs.provider/set-last-modified.error", fileObject);
+ }
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("vfs.provider/set-last-modified.error", fileObject, e);
+ }
+ }
+
+ /**
+ * Checks if an attribute exists.
+ * @param attrName The name of the attribute to check.
+ * @return true if the attribute is associated with the file.
+ * @throws FileSystemException if an error occurs.
+ * @since 2.0
+ */
+ @Override
+ public boolean hasAttribute(final String attrName) throws FileSystemException
+ {
+ if (!fileObject.getType().hasAttributes())
+ {
+ throw new FileSystemException("vfs.provider/exists-attributes-no-exist.error", fileObject);
+ }
+ getAttributes();
+ return attrs.containsKey(attrName);
+ }
+
+ /**
+ * Returns a read-only map of this file's attributes.
+ * @return a Map of the file's attributes.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public Map<String, Object> getAttributes() throws FileSystemException
+ {
+ if (!fileObject.getType().hasAttributes())
+ {
+ throw new FileSystemException("vfs.provider/get-attributes-no-exist.error", fileObject);
+ }
+ if (resetAttributes || roAttrs == null)
+ {
+ try
+ {
+ synchronized (this)
+ {
+ attrs = fileObject.doGetAttributes();
+ roAttrs = Collections.unmodifiableMap(attrs);
+ resetAttributes = false;
+ }
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("vfs.provider/get-attributes.error", fileObject, e);
+ }
+ }
+ return roAttrs;
+ }
+
+ /**
+ * Used internally to flag situations where the file attributes should be
+ * reretrieved.
+ * @since 2.0
+ */
+ public void resetAttributes()
+ {
+ resetAttributes = true;
+ }
+
+ /**
+ * Lists the attributes of this file.
+ * @return An array of attribute names.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public String[] getAttributeNames() throws FileSystemException
+ {
+ getAttributes();
+ final Set<String> names = attrs.keySet();
+ return names.toArray(new String[names.size()]);
+ }
+
+ /**
+ * Gets the value of an attribute.
+ * @param attrName The attribute name.
+ * @return The value of the attribute or null.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public Object getAttribute(final String attrName)
+ throws FileSystemException
+ {
+ getAttributes();
+ return attrs.get(attrName);
+ }
+
+ /**
+ * Sets the value of an attribute.
+ * @param attrName The name of the attribute to add.
+ * @param value The value of the attribute.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public void setAttribute(final String attrName, final Object value)
+ throws FileSystemException
+ {
+ if (!fileObject.getType().hasAttributes())
+ {
+ throw new FileSystemException("vfs.provider/set-attribute-no-exist.error", attrName, fileObject);
+ }
+ try
+ {
+ fileObject.doSetAttribute(attrName, value);
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("vfs.provider/set-attribute.error", e, attrName, fileObject);
+ }
+
+ if (attrs != null)
+ {
+ attrs.put(attrName, value);
+ }
+ }
+
+ /**
+ * Removes an attribute.
+ * @param attrName The name of the attribute to remove.
+ * @throws FileSystemException if an error occurs.
+ * @since 2.0
+ */
+ @Override
+ public void removeAttribute(final String attrName) throws FileSystemException
+ {
+ if (!fileObject.getType().hasAttributes())
+ {
+ throw new FileSystemException("vfs.provider/remove-attribute-no-exist.error", fileObject);
+ }
+
+ try
+ {
+ fileObject.doRemoveAttribute(attrName);
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("vfs.provider/remove-attribute.error", e, attrName, fileObject);
+ }
+
+ if (attrs != null)
+ {
+ attrs.remove(attrName);
+ }
+ }
+
+ /**
+ * Returns the certificates used to sign this file.
+ * @return An array of Certificates.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public Certificate[] getCertificates() throws FileSystemException
+ {
+ if (!fileObject.exists())
+ {
+ throw new FileSystemException("vfs.provider/get-certificates-no-exist.error", fileObject);
+ }
+ /*
+ if (getThreadData().getState() == STATE_WRITING || getThreadData().getState() == STATE_RANDOM_ACCESS)
+ {
+ throw new FileSystemException("vfs.provider/get-certificates-writing.error", file);
+ }
+ */
+
+ try
+ {
+ final Certificate[] certs = fileObject.doGetCertificates();
+ if (certs != null)
+ {
+ return certs;
+ }
+ else
+ {
+ return new Certificate[0];
+ }
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("vfs.provider/get-certificates.error", fileObject, e);
+ }
+ }
+
+ /**
+ * Returns an input stream for reading the content.
+ * @return The InputStream
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public InputStream getInputStream() throws FileSystemException
+ {
+ /*
+ if (getThreadData().getState() == STATE_WRITING || getThreadData().getState() == STATE_RANDOM_ACCESS)
+ {
+ throw new FileSystemException("vfs.provider/read-in-use.error", file);
+ }
+ */
+
+ // Get the raw input stream
+ final InputStream instr = fileObject.getInputStream();
+
+ final InputStream wrappedInstr = new FileContentInputStream(fileObject, instr);
+
+ getOrCreateThreadData().addInstr(wrappedInstr);
+ streamOpened();
+
+ return wrappedInstr;
+ }
+
+ /**
+ * Returns an input/output stream to use to read and write the content of the file in an
+ * random manner.
+ * @param mode The RandomAccessMode.
+ * @return A RandomAccessContent object to access the file.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public RandomAccessContent getRandomAccessContent(final RandomAccessMode mode) throws FileSystemException
+ {
+ /*
+ if (getThreadData().getState() != STATE_NONE)
+ {
+ throw new FileSystemException("vfs.provider/read-in-use.error", file);
+ }
+ */
+
+ // Get the content
+ final RandomAccessContent rastr = fileObject.getRandomAccessContent(mode);
+
+ final FileRandomAccessContent rac = new FileRandomAccessContent(fileObject, rastr);
+
+ getOrCreateThreadData().addRastr(rac);
+ streamOpened();
+
+ return rac;
+ }
+
+ /**
+ * Returns an output stream for writing the content.
+ * @return The OutputStream for the file.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public OutputStream getOutputStream() throws FileSystemException
+ {
+ return getOutputStream(false);
+ }
+
+ /**
+ * Returns an output stream for writing the content in append mode.
+ * @param bAppend true if the data written should be appended.
+ * @return The OutputStream for the file.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public OutputStream getOutputStream(final boolean bAppend) throws FileSystemException
+ {
+ /*
+ if (getThreadData().getState() != STATE_NONE)
+ */
+ FileContentThreadData streams = getOrCreateThreadData();
+ if (streams.getOutstr() != null)
+ {
+ throw new FileSystemException("vfs.provider/write-in-use.error", fileObject);
+ }
+
+ // Get the raw output stream
+ final OutputStream outstr = fileObject.getOutputStream(bAppend);
+
+ // Create and set wrapper
+ FileContentOutputStream wrapped = new FileContentOutputStream(fileObject, outstr);
+ streams.setOutstr(wrapped);
+ streamOpened();
+
+ return wrapped;
+ }
+
+ /**
+ * Closes all resources used by the content, including all streams, readers
+ * and writers.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public void close() throws FileSystemException
+ {
+ FileSystemException caught = null;
+ try
+ {
+ final FileContentThreadData streams = getOrCreateThreadData();
+
+ // Close the input stream
+ while (streams.getInstrsSize() > 0)
+ {
+ final FileContentInputStream instr = (FileContentInputStream) streams.removeInstr(0);
+ try
+ {
+ instr.close();
+ }
+ catch (final FileSystemException ex)
+ {
+ caught = ex;
+
+ }
+ }
+
+ // Close the randomAccess stream
+ while (streams.getRastrsSize() > 0)
+ {
+ final FileRandomAccessContent ra = (FileRandomAccessContent) streams.removeRastr(0);
+ try
+ {
+ ra.close();
+ }
+ catch (final FileSystemException ex)
+ {
+ caught = ex;
+ }
+ }
+
+ // Close the output stream
+ final FileContentOutputStream outstr = streams.getOutstr();
+ if (outstr != null)
+ {
+ streams.setOutstr(null);
+ try
+ {
+ outstr.close();
+ }
+ catch (final FileSystemException ex)
+ {
+ caught = ex;
+ }
+ }
+ }
+ finally
+ {
+ threadData.remove();
+ }
+
+ // throw last error (out >> rac >> input) after all closes have been tried
+ if (caught != null)
+ {
+ throw caught;
+ }
+ }
+
+ /**
+ * Handles the end of input stream.
+ */
+ private void endInput(final FileContentInputStream instr)
+ {
+ FileContentThreadData streams = threadData.get();
+ if (streams != null)
+ {
+ streams.removeInstr(instr);
+ }
+ if (streams == null || !streams.hasStreams())
+ {
+ // remove even when no value is set to remove key
+ threadData.remove();
+ }
+ streamClosed();
+ }
+
+ /**
+ * Handles the end of random access.
+ */
+ private void endRandomAccess(final RandomAccessContent rac)
+ {
+ FileContentThreadData streams = threadData.get();
+ if (streams != null)
+ {
+ streams.removeRastr(rac);
+ }
+ if (streams == null || !streams.hasStreams())
+ {
+ // remove even when no value is set to remove key
+ threadData.remove();
+ }
+ streamClosed();
+ }
+
+ /**
+ * Handles the end of output stream.
+ */
+ private void endOutput() throws Exception
+ {
+ FileContentThreadData streams = threadData.get();
+ if (streams != null)
+ {
+ streams.setOutstr(null);
+ }
+ if (streams == null || !streams.hasStreams())
+ {
+ // remove even when no value is set to remove key
+ threadData.remove();
+ }
+ streamClosed();
+ fileObject.endOutput();
+ }
+
+ /**
+ * Check if a input and/or output stream is open.
+ * <p>
+ * This checks only the scope of the current thread.
+ *
+ * @return true if this is the case
+ */
+ @Override
+ public boolean isOpen()
+ {
+ FileContentThreadData streams = threadData.get();
+ if (streams != null && streams.hasStreams())
+ {
+ return true;
+ }
+ else
+ {
+ // threadData.get() created empty entry
+ threadData.remove();
+ return false;
+ }
+ }
+
+ /**
+ * Check if a input and/or output stream is open.
+ * This checks all threads.
+ *
+ * @return true if this is the case
+ */
+ public boolean isOpenGlobal()
+ {
+ synchronized (this)
+ {
+ return openStreams > 0;
+ }
+ }
+
+ /**
+ * An input stream for reading content. Provides buffering, and
+ * end-of-stream monitoring.
+ */
+ private final class FileContentInputStream extends MonitorInputStream
+ {
+ // avoid gc
+ private final FileObject file;
+
+ FileContentInputStream(final FileObject file, final InputStream instr)
+ {
+ super(instr);
+ this.file = file;
+ }
+
+ /**
+ * Closes this input stream.
+ */
+ @Override
+ public void close() throws FileSystemException
+ {
+ try
+ {
+ super.close();
+ }
+ catch (final IOException e)
+ {
+ throw new FileSystemException("vfs.provider/close-instr.error", file, e);
+ }
+ }
+
+ /**
+ * Called after the stream has been closed.
+ */
+ @Override
+ protected void onClose() throws IOException
+ {
+ try
+ {
+ super.onClose();
+ }
+ finally
+ {
+ endInput(this);
+ }
+ }
+ }
+
+ /**
+ * An input/output stream for reading/writing content on random positions
+ */
+ private final class FileRandomAccessContent extends MonitorRandomAccessContent
+ {
+ // also avoids gc
+ private final FileObject file;
+
+ FileRandomAccessContent(final FileObject file, final RandomAccessContent content)
+ {
+ super(content);
+ this.file = file;
+ }
+
+ /**
+ * Called after the stream has been closed.
+ */
+ @Override
+ protected void onClose() throws IOException
+ {
+ try
+ {
+ super.onClose();
+ }
+ finally
+ {
+ endRandomAccess(this);
+ }
+ }
+
+ @Override
+ public void close() throws FileSystemException
+ {
+ try
+ {
+ super.close();
+ }
+ catch (final IOException e)
+ {
+ throw new FileSystemException("vfs.provider/close-rac.error", file, e);
+ }
+ }
+ }
+
+ /**
+ * An output stream for writing content.
+ */
+ final class FileContentOutputStream extends MonitorOutputStream
+ {
+ // avoid gc
+ private final FileObject file;
+
+ FileContentOutputStream(final FileObject file, final OutputStream outstr)
+ {
+ super(outstr);
+ this.file = file;
+ }
+
+ /**
+ * Closes this output stream.
+ */
+ @Override
+ public void close() throws FileSystemException
+ {
+ try
+ {
+ super.close();
+ }
+ catch (final IOException e)
+ {
+ throw new FileSystemException("vfs.provider/close-outstr.error", file, e);
+ }
+ }
+
+ /**
+ * Called after this stream is closed.
+ */
+ @Override
+ protected void onClose() throws IOException
+ {
+ try
+ {
+ super.onClose();
+ }
+ finally
+ {
+ try
+ {
+ endOutput();
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("vfs.provider/close-outstr.error", file, e);
+ }
+ }
+ }
+ }
+
+ /**
+ * get the content info. e.g. content-type, content-encoding
+ * @return The FileContentInfo.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileContentInfo getContentInfo() throws FileSystemException
+ {
+ if (fileContentInfo == null)
+ {
+ fileContentInfo = fileContentInfoFactory.create(this);
+ }
+
+ return fileContentInfo;
+ }
+
+ /**
+ * Writes this content to another FileContent.
+ *
+ * @param fileContent
+ * The target FileContent.
+ * @return the total number of bytes written
+ * @throws IOException
+ * if an error occurs writing the content.
+ * @since 2.1
+ */
+ @Override
+ public long write(final FileContent fileContent) throws IOException
+ {
+ final OutputStream output = fileContent.getOutputStream();
+ try
+ {
+ return this.write(output);
+ }
+ finally
+ {
+ output.close();
+ }
+ }
+
+ /**
+ * Writes this content to another FileObject.
+ *
+ * @param file
+ * The target FileObject.
+ * @return the total number of bytes written
+ * @throws IOException
+ * if an error occurs writing the content.
+ * @since 2.1
+ */
+ @Override
+ public long write(final FileObject file) throws IOException
+ {
+ return write(file.getContent());
+ }
+
+ /**
+ * Writes this content to an OutputStream.
+ *
+ * @param output
+ * The target OutputStream.
+ * @return the total number of bytes written
+ * @throws IOException
+ * if an error occurs writing the content.
+ * @since 2.1
+ */
+ @Override
+ public long write(final OutputStream output) throws IOException
+ {
+ return write(output, WRITE_BUFFER_SIZE);
+ }
+
+ /**
+ * Writes this content to an OutputStream.
+ *
+ * @param output
+ * The target OutputStream.
+ * @param bufferSize
+ * The buffer size to write data chunks.
+ * @return the total number of bytes written
+ * @throws IOException
+ * if an error occurs writing the file.
+ * @since 2.1
+ */
+ @Override
+ public long write(final OutputStream output, final int bufferSize) throws IOException
+ {
+ final InputStream input = this.getInputStream();
+ long count = 0;
+ try
+ {
+ // This read/write code from Apache Commons IO
+ final byte[] buffer = new byte[bufferSize];
+ int n = 0;
+ while (-1 != (n = input.read(buffer)))
+ {
+ output.write(buffer, 0, n);
+ count += n;
+ }
+ }
+ finally
+ {
+ input.close();
+ }
+ return count;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/DefaultFileSelectorInfo.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/DefaultFileSelectorInfo.java
new file mode 100644
index 0000000..c38fb3f
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/DefaultFileSelectorInfo.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSelectInfo;
+
+/**
+ * A default {@link FileSelectInfo} implementation.
+ */
+final class DefaultFileSelectorInfo
+ implements FileSelectInfo
+{
+ private FileObject baseFolder;
+ private FileObject file;
+ private int depth;
+
+ @Override
+ public FileObject getBaseFolder()
+ {
+ return baseFolder;
+ }
+
+ public void setBaseFolder(final FileObject baseFolder)
+ {
+ this.baseFolder = baseFolder;
+ }
+
+ @Override
+ public FileObject getFile()
+ {
+ return file;
+ }
+
+ public void setFile(final FileObject file)
+ {
+ this.file = file;
+ }
+
+ @Override
+ public int getDepth()
+ {
+ return depth;
+ }
+
+ public void setDepth(final int depth)
+ {
+ this.depth = depth;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/DefaultURLConnection.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/DefaultURLConnection.java
new file mode 100644
index 0000000..a7ce5dd
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/DefaultURLConnection.java
@@ -0,0 +1,138 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.URL;
+import java.net.URLConnection;
+
+import org.apache.commons.vfs2.FileContent;
+import org.apache.commons.vfs2.FileSystemException;
+
+/**
+ * A default URL connection that will work for most file systems.
+ */
+public final class DefaultURLConnection
+ extends URLConnection
+{
+ private final FileContent content;
+
+ public DefaultURLConnection(final URL url,
+ final FileContent content)
+ {
+ super(url);
+ this.content = content;
+ }
+
+ @Override
+ public void connect()
+ {
+ connected = true;
+ }
+
+ @Override
+ public InputStream getInputStream()
+ throws IOException
+ {
+ return content.getInputStream();
+ }
+
+ @Override
+ public OutputStream getOutputStream()
+ throws IOException
+ {
+ return content.getOutputStream();
+ }
+
+
+ @Override
+ public long getLastModified()
+ {
+ try
+ {
+ return content.getLastModifiedTime();
+ }
+ catch (final FileSystemException ignored)
+ {
+ return -1; // TODO: report?
+ }
+ }
+
+ @Override
+ public int getContentLength()
+ {
+ try
+ {
+ return (int) content.getSize();
+ }
+ catch (final FileSystemException fse)
+ {
+ return -1; // TODO: report?
+ }
+ }
+
+ @Override
+ public String getContentType()
+ {
+ try
+ {
+ return content.getContentInfo().getContentType();
+ }
+ catch (final FileSystemException e)
+ {
+ throw new RuntimeException(e.getMessage());
+ }
+ }
+
+ @Override
+ public String getContentEncoding()
+ {
+ try
+ {
+ return content.getContentInfo().getContentEncoding();
+ }
+ catch (final FileSystemException e)
+ {
+ throw new RuntimeException(e.getMessage());
+ }
+ }
+
+ /*
+ public String getHeaderField(String name)
+ {
+ try
+ {
+ if (content.getFile().getFileSystem().hasCapability(Capability.ATTRIBUTES))
+ {
+ String value = (String) content.getAttribute(name);
+ if (value != null)
+ {
+ return value;
+ }
+ }
+
+ return null;
+ }
+ catch (FileSystemException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+ */
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/DefaultURLStreamHandler.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/DefaultURLStreamHandler.java
new file mode 100644
index 0000000..4c925c9
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/DefaultURLStreamHandler.java
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import java.io.IOException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.net.URLStreamHandler;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+
+/**
+ * A default URL stream handler that will work for most file systems.
+ */
+public class DefaultURLStreamHandler
+ extends URLStreamHandler
+{
+ private final VfsComponentContext context;
+ private final FileSystemOptions fileSystemOptions;
+
+ public DefaultURLStreamHandler(final VfsComponentContext context)
+ {
+ this(context, null);
+ }
+
+ public DefaultURLStreamHandler(final VfsComponentContext context, final FileSystemOptions fileSystemOptions)
+ {
+ this.context = context;
+ this.fileSystemOptions = fileSystemOptions;
+ }
+
+ @Override
+ protected URLConnection openConnection(final URL url)
+ throws IOException
+ {
+ final FileObject entry = context.resolveFile(url.toExternalForm(), fileSystemOptions);
+ return new DefaultURLConnection(url, entry.getContent());
+ }
+
+ @Override
+ protected void parseURL(final URL u,
+ final String spec,
+ final int start,
+ final int limit)
+ {
+ try
+ {
+ final FileObject old = context.resolveFile(u.toExternalForm(), fileSystemOptions);
+
+ FileObject newURL;
+ if (start > 0 && spec.charAt(start - 1) == ':')
+ {
+ newURL = context.resolveFile(old, spec, fileSystemOptions);
+ }
+ else
+ {
+ if (old.isFile() && old.getParent() != null)
+ {
+ // for files we have to resolve relative
+ newURL = old.getParent().resolveFile(spec);
+ }
+ else
+ {
+ newURL = old.resolveFile(spec);
+ }
+ }
+
+ final String url = newURL.getName().getURI();
+ final StringBuilder filePart = new StringBuilder();
+ final String protocolPart = UriParser.extractScheme(url, filePart);
+
+ setURL(u, protocolPart, "", -1, null, null, filePart.toString(), null, null);
+ }
+ catch (final FileSystemException fse)
+ {
+ // This is rethrown to MalformedURLException in URL anyway
+ throw new RuntimeException(fse.getMessage());
+ }
+ }
+
+ @Override
+ protected String toExternalForm(final URL u)
+ {
+ return u.getProtocol() + ":" + u.getFile();
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/DelegateFileObject.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/DelegateFileObject.java
new file mode 100644
index 0000000..bb397e4
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/DelegateFileObject.java
@@ -0,0 +1,488 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.security.cert.Certificate;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import org.apache.commons.vfs2.FileChangeEvent;
+import org.apache.commons.vfs2.FileContentInfo;
+import org.apache.commons.vfs2.FileListener;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileNotFolderException;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.RandomAccessContent;
+import org.apache.commons.vfs2.util.RandomAccessMode;
+import org.apache.commons.vfs2.util.WeakRefFileListener;
+
+/**
+ * A file backed by another file.
+ * <p>
+ * TODO - Extract subclass that overlays the children.
+ *
+ * @param <AFS> A subclass of AbstractFileSystem.
+ */
+public class DelegateFileObject<AFS extends AbstractFileSystem> extends AbstractFileObject<AFS> implements FileListener
+{
+ private FileObject file;
+ private final Set<String> children = new HashSet<String>();
+ private boolean ignoreEvent;
+
+ public DelegateFileObject(final AbstractFileName name,
+ final AFS fileSystem,
+ final FileObject file) throws FileSystemException
+ {
+ super(name, fileSystem);
+ this.file = file;
+ if (file != null)
+ {
+ WeakRefFileListener.installListener(file, this);
+ }
+ }
+
+ /**
+ * Get access to the delegated file.
+ * @return The FileObject.
+ * @since 2.0
+ */
+ public FileObject getDelegateFile()
+ {
+ return file;
+ }
+
+ /**
+ * Adds a child to this file.
+ * @param baseName The base FileName.
+ * @param type The FileType.
+ * @throws Exception if an error occurs.
+ */
+ public void attachChild(final FileName baseName, final FileType type) throws Exception
+ {
+ final FileType oldType = doGetType();
+ if (children.add(baseName.getBaseName()))
+ {
+ childrenChanged(baseName, type);
+ }
+ maybeTypeChanged(oldType);
+ }
+
+ /**
+ * Attaches or detaches the target file.
+ * @param file The FileObject.
+ * @throws Exception if an error occurs.
+ */
+ public void setFile(final FileObject file) throws Exception
+ {
+ final FileType oldType = doGetType();
+
+ if (file != null)
+ {
+ WeakRefFileListener.installListener(file, this);
+ }
+ this.file = file;
+ maybeTypeChanged(oldType);
+ }
+
+ /**
+ * Checks whether the file's type has changed, and fires the appropriate
+ * events.
+ * @param oldType The old FileType.
+ * @throws Exception if an error occurs.
+ */
+ private void maybeTypeChanged(final FileType oldType) throws Exception
+ {
+ final FileType newType = doGetType();
+ if (oldType == FileType.IMAGINARY && newType != FileType.IMAGINARY)
+ {
+ handleCreate(newType);
+ }
+ else if (oldType != FileType.IMAGINARY && newType == FileType.IMAGINARY)
+ {
+ handleDelete();
+ }
+ }
+
+ /**
+ * Determines the type of the file, returns null if the file does not
+ * exist.
+ */
+ @Override
+ protected FileType doGetType() throws FileSystemException
+ {
+ if (file != null)
+ {
+ return file.getType();
+ }
+ else if (children.size() > 0)
+ {
+ return FileType.FOLDER;
+ }
+ else
+ {
+ return FileType.IMAGINARY;
+ }
+ }
+
+ /**
+ * Determines if this file can be read.
+ */
+ @Override
+ protected boolean doIsReadable() throws FileSystemException
+ {
+ if (file != null)
+ {
+ return file.isReadable();
+ }
+ else
+ {
+ return true;
+ }
+ }
+
+ /**
+ * Determines if this file can be written to.
+ */
+ @Override
+ protected boolean doIsWriteable() throws FileSystemException
+ {
+ if (file != null)
+ {
+ return file.isWriteable();
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ /**
+ * Determines if this file is executable.
+ */
+ @Override
+ protected boolean doIsExecutable() throws FileSystemException
+ {
+ if (file != null)
+ {
+ return file.isExecutable();
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ /**
+ * Determines if this file is hidden.
+ */
+ @Override
+ protected boolean doIsHidden() throws FileSystemException
+ {
+ if (file != null)
+ {
+ return file.isHidden();
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ /**
+ * Lists the children of the file.
+ */
+ @Override
+ protected String[] doListChildren() throws Exception
+ {
+ if (file != null)
+ {
+ final FileObject[] children;
+
+ try
+ {
+ children = file.getChildren();
+ }
+ // VFS-210
+ catch (final FileNotFolderException e)
+ {
+ throw new FileNotFolderException(getName(), e);
+ }
+
+ final String[] childNames = new String[children.length];
+ for (int i = 0; i < children.length; i++)
+ {
+ childNames[i] = children[i].getName().getBaseName();
+ }
+ return childNames;
+ }
+ else
+ {
+ return children.toArray(new String[children.size()]);
+ }
+ }
+
+ /**
+ * Creates this file as a folder.
+ */
+ @Override
+ protected void doCreateFolder() throws Exception
+ {
+ ignoreEvent = true;
+ try
+ {
+ file.createFolder();
+ }
+ finally
+ {
+ ignoreEvent = false;
+ }
+ }
+
+ /**
+ * Deletes the file.
+ */
+ @Override
+ protected void doDelete() throws Exception
+ {
+ ignoreEvent = true;
+ try
+ {
+ file.delete();
+ }
+ finally
+ {
+ ignoreEvent = false;
+ }
+ }
+
+ /**
+ * Returns the size of the file content (in bytes). Is only called if
+ * {@link #doGetType} returns {@link FileType#FILE}.
+ */
+ @Override
+ protected long doGetContentSize() throws Exception
+ {
+ return file.getContent().getSize();
+ }
+
+ /**
+ * Returns the attributes of this file.
+ */
+ @Override
+ protected Map<String, Object> doGetAttributes()
+ throws Exception
+ {
+ return file.getContent().getAttributes();
+ }
+
+ /**
+ * Sets an attribute of this file.
+ */
+ @Override
+ protected void doSetAttribute(final String atttrName,
+ final Object value)
+ throws Exception
+ {
+ file.getContent().setAttribute(atttrName, value);
+ }
+
+ /**
+ * Returns the certificates of this file.
+ */
+ @Override
+ protected Certificate[] doGetCertificates() throws Exception
+ {
+ return file.getContent().getCertificates();
+ }
+
+ /**
+ * Returns the last-modified time of this file.
+ */
+ @Override
+ protected long doGetLastModifiedTime() throws Exception
+ {
+ return file.getContent().getLastModifiedTime();
+ }
+
+ /**
+ * Sets the last-modified time of this file.
+ * @since 2.0
+ */
+ @Override
+ protected boolean doSetLastModifiedTime(final long modtime)
+ throws Exception
+ {
+ file.getContent().setLastModifiedTime(modtime);
+ return true;
+ }
+
+ /**
+ * Creates an input stream to read the file content from.
+ */
+ @Override
+ protected InputStream doGetInputStream() throws Exception
+ {
+ return file.getContent().getInputStream();
+ }
+
+ /**
+ * Creates an output stream to write the file content to.
+ */
+ @Override
+ protected OutputStream doGetOutputStream(final boolean bAppend) throws Exception
+ {
+ return file.getContent().getOutputStream(bAppend);
+ }
+
+ /**
+ * Called when a file is created.
+ * @param event The FileChangeEvent.
+ * @throws Exception if an error occurs.
+ */
+ @Override
+ public void fileCreated(final FileChangeEvent event) throws Exception
+ {
+ if (event.getFile() != file)
+ {
+ return;
+ }
+ if (!ignoreEvent)
+ {
+ handleCreate(file.getType());
+ }
+ }
+
+ /**
+ * Called when a file is deleted.
+ * @param event The FileChangeEvent.
+ * @throws Exception if an error occurs.
+ */
+ @Override
+ public void fileDeleted(final FileChangeEvent event) throws Exception
+ {
+ if (event.getFile() != file)
+ {
+ return;
+ }
+ if (!ignoreEvent)
+ {
+ handleDelete();
+ }
+ }
+
+ /**
+ * Called when a file is changed.
+ * <p>
+ * This will only happen if you monitor the file using {@link org.apache.commons.vfs2.FileMonitor}.
+ *
+ * @param event The FileChangeEvent.
+ * @throws Exception if an error occurs.
+ */
+ @Override
+ public void fileChanged(final FileChangeEvent event) throws Exception
+ {
+ if (event.getFile() != file)
+ {
+ return;
+ }
+ if (!ignoreEvent)
+ {
+ handleChanged();
+ }
+ }
+
+ /**
+ * Close the delegated file.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public void close() throws FileSystemException
+ {
+ super.close();
+
+ if (file != null)
+ {
+ file.close();
+ }
+ }
+
+ /**
+ * Refresh file information.
+ * @throws FileSystemException if an error occurs.
+ * @since 2.0
+ */
+ @Override
+ public void refresh() throws FileSystemException
+ {
+ super.refresh();
+ if (file != null)
+ {
+ file.refresh();
+ }
+ }
+
+ /**
+ * Return file content info.
+ * @return the file content info of the delegee.
+ * @throws Exception Any thrown Exception is wrapped in FileSystemException.
+ * @since 2.0
+ */
+ protected FileContentInfo doGetContentInfo() throws Exception
+ {
+ return file.getContent().getContentInfo();
+ }
+
+ /**
+ * Renames the file.
+ *
+ * @param newFile the new location/name.
+ * @throws Exception Any thrown Exception is wrapped in FileSystemException.
+ * @since 2.0
+ */
+ @Override
+ protected void doRename(final FileObject newFile)
+ throws Exception
+ {
+ file.moveTo(((DelegateFileObject) newFile).file);
+ }
+
+ /**
+ * Removes an attribute of this file.
+ * @since 2.0
+ */
+ @Override
+ protected void doRemoveAttribute(final String atttrName)
+ throws Exception
+ {
+ file.getContent().removeAttribute(atttrName);
+ }
+
+ /**
+ * Creates access to the file for random i/o.
+ * @since 2.0
+ */
+ @Override
+ protected RandomAccessContent doGetRandomAccessContent(final RandomAccessMode mode) throws Exception
+ {
+ return file.getContent().getRandomAccessContent(mode);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/FileContentThreadData.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/FileContentThreadData.java
new file mode 100644
index 0000000..4bad311
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/FileContentThreadData.java
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import java.io.InputStream;
+import java.util.ArrayList;
+
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.RandomAccessContent;
+
+/**
+ * Holds the data which needs to be local to the current thread
+ */
+class FileContentThreadData
+{
+ // private int state = DefaultFileContent.STATE_CLOSED;
+
+ private final ArrayList<InputStream> instrs = new ArrayList<InputStream>();
+ private final ArrayList<RandomAccessContent> rastrs = new ArrayList<RandomAccessContent>();
+ private DefaultFileContent.FileContentOutputStream outstr;
+
+ FileContentThreadData()
+ {
+ }
+
+ /*
+ int getState()
+ {
+ return state;
+ }
+
+ void setState(int state)
+ {
+ this.state = state;
+ }
+ */
+
+ void addInstr(final InputStream is)
+ {
+ this.instrs.add(is);
+ }
+
+ void setOutstr(final DefaultFileContent.FileContentOutputStream os)
+ {
+ this.outstr = os;
+ }
+
+ DefaultFileContent.FileContentOutputStream getOutstr()
+ {
+ return this.outstr;
+ }
+
+ void addRastr(final RandomAccessContent ras)
+ {
+ this.rastrs.add(ras);
+ }
+
+ int getInstrsSize()
+ {
+ return this.instrs.size();
+ }
+
+ public Object removeInstr(final int pos)
+ {
+ return this.instrs.remove(pos);
+ }
+
+ public void removeInstr(final InputStream instr)
+ {
+ this.instrs.remove(instr);
+ }
+
+ public Object removeRastr(final int pos)
+ {
+ return this.rastrs.remove(pos);
+ }
+
+ public void removeRastr(final RandomAccessContent ras)
+ {
+ this.rastrs.remove(ras);
+ }
+
+ public boolean hasStreams()
+ {
+ return instrs.size() > 0 || outstr != null || rastrs.size() > 0;
+ }
+
+ public void closeOutstr() throws FileSystemException
+ {
+ outstr.close();
+ outstr = null;
+ }
+
+ int getRastrsSize()
+ {
+ return rastrs.size();
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/FileNameParser.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/FileNameParser.java
new file mode 100644
index 0000000..5370507
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/FileNameParser.java
@@ -0,0 +1,44 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystemException;
+
+/**
+ * Provides methods to parse a filename into a {@link org.apache.commons.vfs2.FileName}.
+ */
+public interface FileNameParser
+{
+ /**
+ * Check if a character needs encoding (%nn).
+ * @param ch the character
+ * @return true if character should be encoded
+ */
+ boolean encodeCharacter(char ch);
+
+ /**
+ * parses a String into a filename.
+ * @param context The component context.
+ * @param base The base FileName.
+ * @param uri The target file name.
+ * @return A FileName that represents the taret file.
+ * @throws FileSystemException if an error occurs parsing the URI.
+ */
+ FileName parseUri(final VfsComponentContext context, final FileName base, final String uri)
+ throws FileSystemException;
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/FileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/FileProvider.java
new file mode 100644
index 0000000..7f0ee30
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/FileProvider.java
@@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import java.util.Collection;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemConfigBuilder;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+
+
+/**
+ * A file provider. Each file provider is responsible for handling files for
+ * a particular URI scheme.
+ * <p>
+ * A file provider may also implement {@link VfsComponent}.
+ */
+public interface FileProvider
+{
+ /**
+ * Locates a file object, by absolute URI.
+ *
+ * @param baseFile The base file to use for resolving the individual parts of
+ * a compound URI.
+ * @param uri The absolute URI of the file to find.
+ * @param fileSystemOptions The FileSystemOptions
+ * @return The FileObject.
+ * @throws FileSystemException if an error occurs locating the file.
+ */
+ FileObject findFile(final FileObject baseFile, final String uri, final FileSystemOptions fileSystemOptions)
+ throws FileSystemException;
+
+ /**
+ * Creates a layered file system.
+ *
+ * @param scheme The URI scheme for the layered file system.
+ * @param file The file to build the file system on.
+ * @param fileSystemOptions The FileSystemOptions.
+ * @return A FileObject in the file system.
+ * @throws FileSystemException if an error occurs.
+ */
+ FileObject createFileSystem(String scheme, FileObject file, FileSystemOptions fileSystemOptions)
+ throws FileSystemException;
+
+ /**
+ * Gets the configbuilder useable to collect the needed fileSystemOptions.
+ * @return a FileSystemConfigBuilder for the particular file system.
+ */
+ FileSystemConfigBuilder getConfigBuilder();
+
+ /**
+ * Get the filesystem capabilities.<br>
+ * These are the same as on the filesystem, but available before the first filesystem was
+ * instanciated.
+ * @return a Collection of the file systems Capabilities.
+ */
+ Collection<Capability> getCapabilities();
+
+ /**
+ * Parse the URI into a FileName.
+ * @param root The base FileName.
+ * @param uri The file to be accessed.
+ * @return A FileName representing the target file.
+ * @throws FileSystemException if an error occurs.
+ */
+ FileName parseUri(FileName root, String uri) throws FileSystemException;
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/FileReplicator.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/FileReplicator.java
new file mode 100644
index 0000000..7a14ee6
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/FileReplicator.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import java.io.File;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSelector;
+import org.apache.commons.vfs2.FileSystemException;
+
+/**
+ * Responsible for making local replicas of files.
+ * <p>
+ * A file replicator may also implement {@link VfsComponent}.
+ */
+public interface FileReplicator
+{
+ /**
+ * Creates a local copy of the file, and all its descendants.
+ *
+ * @param srcFile The file to copy.
+ * @param selector Selects the files to copy.
+ * @return The local copy of the source file.
+ * @throws FileSystemException If the source files does not exist, or on error copying.
+ */
+ File replicateFile(FileObject srcFile, FileSelector selector)
+ throws FileSystemException;
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/FileSystemKey.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/FileSystemKey.java
new file mode 100644
index 0000000..cc468e1
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/FileSystemKey.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import org.apache.commons.vfs2.FileSystemOptions;
+
+/**
+ * Used to identify a filesystem
+ */
+class FileSystemKey implements Comparable<FileSystemKey>
+{
+ private static final FileSystemOptions EMPTY_OPTIONS = new FileSystemOptions();
+
+ private final Comparable<?> key;
+ private final FileSystemOptions fileSystemOptions;
+
+ /**
+ * Create the FS key.
+ *
+ * @param key must implement Comparable, and must be self-comparable
+ * @param fileSystemOptions the required options
+ */
+ FileSystemKey(final Comparable<?> key, final FileSystemOptions fileSystemOptions)
+ {
+ this.key = key;
+ if (fileSystemOptions != null)
+ {
+ this.fileSystemOptions = fileSystemOptions;
+ }
+ else
+ {
+ this.fileSystemOptions = EMPTY_OPTIONS;
+ }
+ }
+
+ @Override
+ public int compareTo(final FileSystemKey o)
+ {
+ @SuppressWarnings("unchecked") // Keys must implement comparable, and be comparable to themselves
+ final
+ Comparable<Comparable<?>> comparable = (Comparable<Comparable<?>>) key;
+ final int ret = comparable.compareTo(o.key);
+ if (ret != 0)
+ {
+ // other filesystem
+ return ret;
+ }
+
+ return fileSystemOptions.compareTo(o.fileSystemOptions);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/GenericFileName.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/GenericFileName.java
new file mode 100644
index 0000000..112be29
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/GenericFileName.java
@@ -0,0 +1,172 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileType;
+
+/**
+ * A file name that represents a 'generic' URI, as per RFC 2396. Consists of
+ * a scheme, userinfo (typically username and password), hostname, port, and
+ * path.
+ */
+public class GenericFileName extends AbstractFileName
+{
+ private static final char[] USERNAME_RESERVED = {':', '@', '/'};
+ private static final char[] PASSWORD_RESERVED = {'@', '/', '?'};
+ private final String userName;
+ private final String hostName;
+ private final int defaultPort;
+ private final String password;
+ private final int port;
+
+ protected GenericFileName(final String scheme,
+ final String hostName,
+ final int port,
+ final int defaultPort,
+ final String userName,
+ final String password,
+ final String path,
+ final FileType type
+ )
+ {
+ super(scheme, path, type);
+ this.hostName = hostName;
+ this.defaultPort = defaultPort;
+ this.password = password;
+ this.userName = userName;
+ if (port > 0)
+ {
+ this.port = port;
+ }
+ else
+ {
+ this.port = getDefaultPort();
+ }
+ }
+
+ /**
+ * Returns the user name part of this name.
+ * @return The user name.
+ */
+ public String getUserName()
+ {
+ return userName;
+ }
+
+ /**
+ * Returns the password part of this name.
+ * @return The password.
+ */
+ public String getPassword()
+ {
+ return password;
+ }
+
+ /**
+ * Returns the host name part of this name.
+ * @return The host name.
+ */
+ public String getHostName()
+ {
+ return hostName;
+ }
+
+ /**
+ * Returns the port part of this name.
+ * @return The port number.
+ */
+ public int getPort()
+ {
+ return port;
+ }
+
+ /**
+ * Returns the default port for this file name.
+ * @return The default port number.
+ */
+ public int getDefaultPort()
+ {
+ return defaultPort;
+ }
+
+ /**
+ * Create a FileName.
+ * @param absPath The absolute path.
+ * @param type The FileType.
+ * @return The created FileName.
+ */
+ @Override
+ public FileName createName(final String absPath, final FileType type)
+ {
+ return new GenericFileName(
+ getScheme(),
+ hostName,
+ port,
+ defaultPort,
+ userName,
+ password,
+ absPath,
+ type);
+ }
+
+ /**
+ * Builds the root URI for this file name.
+ */
+ @Override
+ protected void appendRootUri(final StringBuilder buffer, final boolean addPassword)
+ {
+ buffer.append(getScheme());
+ buffer.append("://");
+ appendCredentials(buffer, addPassword);
+ buffer.append(hostName);
+ if (port != getDefaultPort())
+ {
+ buffer.append(':');
+ buffer.append(port);
+ }
+ }
+
+ /**
+ * Append the user credentials.
+ * <p>
+ * If anything was added, it will be '@' terminated.
+ *
+ * @param buffer the string buffer to modify.
+ * @param addPassword flag if password should be added or replaced with placeholder (false).
+ */
+ protected void appendCredentials(final StringBuilder buffer, final boolean addPassword)
+ {
+ if (userName != null && userName.length() != 0)
+ {
+ UriParser.appendEncoded(buffer, userName, USERNAME_RESERVED);
+ if (password != null && password.length() != 0)
+ {
+ buffer.append(':');
+ if (addPassword)
+ {
+ UriParser.appendEncoded(buffer, password, PASSWORD_RESERVED);
+ }
+ else
+ {
+ buffer.append("***");
+ }
+ }
+ buffer.append('@');
+ }
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/HostFileNameParser.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/HostFileNameParser.java
new file mode 100644
index 0000000..07938c1
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/HostFileNameParser.java
@@ -0,0 +1,366 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.util.Cryptor;
+import org.apache.commons.vfs2.util.CryptorFactory;
+
+/**
+ * Implementation for any url based filesystem.
+ * <p>
+ * Parses the url into user/password/host/port/path.
+ * Does not handle a query string (after ?)
+ *
+ * @see URLFileNameParser URLFileNameParser for the implementation which also handles the query string too
+ */
+public class HostFileNameParser extends AbstractFileNameParser
+{
+ private final int defaultPort;
+
+ public HostFileNameParser(final int defaultPort)
+ {
+ this.defaultPort = defaultPort;
+ }
+
+ public int getDefaultPort()
+ {
+ return defaultPort;
+ }
+
+ @Override
+ public FileName parseUri(final VfsComponentContext context, final FileName base, final String filename)
+ throws FileSystemException
+ {
+ // FTP URI are generic URI (as per RFC 2396)
+ final StringBuilder name = new StringBuilder();
+
+ // Extract the scheme and authority parts
+ final Authority auth = extractToPath(filename, name);
+
+ // Decode and normalise the file name
+ UriParser.canonicalizePath(name, 0, name.length(), this);
+ UriParser.fixSeparators(name);
+ final FileType fileType = UriParser.normalisePath(name);
+ final String path = name.toString();
+
+ return new GenericFileName(
+ auth.scheme,
+ auth.hostName,
+ auth.port,
+ defaultPort,
+ auth.userName,
+ auth.password,
+ path,
+ fileType);
+ }
+
+ /**
+ * Extracts the scheme, userinfo, hostname and port components of a
+ * generic URI.
+ *
+ * @param uri The absolute URI to parse.
+ * @param name Used to return the remainder of the URI.
+ * @return Authority extracted host authority, never null.
+ * @throws FileSystemException if authority cannot be extracted.
+ */
+ protected Authority extractToPath(final String uri,
+ final StringBuilder name)
+ throws FileSystemException
+ {
+ final Authority auth = new Authority();
+
+ // Extract the scheme
+ auth.scheme = UriParser.extractScheme(uri, name);
+
+ // Expecting "//"
+ if (name.length() < 2 || name.charAt(0) != '/' || name.charAt(1) != '/')
+ {
+ throw new FileSystemException("vfs.provider/missing-double-slashes.error", uri);
+ }
+ name.delete(0, 2);
+
+ // Extract userinfo, and split into username and password
+ final String userInfo = extractUserInfo(name);
+ final String userName;
+ final String password;
+ if (userInfo != null)
+ {
+ final int idx = userInfo.indexOf(':');
+ if (idx == -1)
+ {
+ userName = userInfo;
+ password = null;
+ }
+ else
+ {
+ userName = userInfo.substring(0, idx);
+ password = userInfo.substring(idx + 1);
+ }
+ }
+ else
+ {
+ userName = null;
+ password = null;
+ }
+ auth.userName = UriParser.decode(userName);
+ auth.password = UriParser.decode(password);
+
+ if (auth.password != null && auth.password.startsWith("{") && auth.password.endsWith("}"))
+ {
+ try
+ {
+ final Cryptor cryptor = CryptorFactory.getCryptor();
+ auth.password = cryptor.decrypt(auth.password.substring(1, auth.password.length() - 1));
+ }
+ catch (final Exception ex)
+ {
+ throw new FileSystemException("Unable to decrypt password", ex);
+ }
+ }
+
+ // Extract hostname, and normalise (lowercase)
+ final String hostName = extractHostName(name);
+ if (hostName == null)
+ {
+ throw new FileSystemException("vfs.provider/missing-hostname.error", uri);
+ }
+ auth.hostName = hostName.toLowerCase();
+
+ // Extract port
+ auth.port = extractPort(name, uri);
+
+ // Expecting '/' or empty name
+ if (name.length() > 0 && name.charAt(0) != '/')
+ {
+ throw new FileSystemException("vfs.provider/missing-hostname-path-sep.error", uri);
+ }
+
+ return auth;
+ }
+
+ /**
+ * Extracts the user info from a URI.
+ *
+ * @param name string buffer with the "scheme://" part has been removed already. Will be modified.
+ * @return the user information up to the '@' or null.
+ */
+ protected String extractUserInfo(final StringBuilder name)
+ {
+ final int maxlen = name.length();
+ for (int pos = 0; pos < maxlen; pos++)
+ {
+ final char ch = name.charAt(pos);
+ if (ch == '@')
+ {
+ // Found the end of the user info
+ final String userInfo = name.substring(0, pos);
+ name.delete(0, pos + 1);
+ return userInfo;
+ }
+ if (ch == '/' || ch == '?')
+ {
+ // Not allowed in user info
+ break;
+ }
+ }
+
+ // Not found
+ return null;
+ }
+
+ /**
+ * Extracts the hostname from a URI.
+ *
+ * @param name string buffer with the "scheme://[userinfo@]" part has been removed already. Will be modified.
+ * @return the host name or null.
+ */
+ protected String extractHostName(final StringBuilder name)
+ {
+ final int maxlen = name.length();
+ int pos = 0;
+ for (; pos < maxlen; pos++)
+ {
+ final char ch = name.charAt(pos);
+ if (ch == '/' || ch == ';' || ch == '?' || ch == ':'
+ || ch == '@' || ch == '&' || ch == '=' || ch == '+'
+ || ch == '$' || ch == ',')
+ {
+ break;
+ }
+ }
+ if (pos == 0)
+ {
+ return null;
+ }
+
+ final String hostname = name.substring(0, pos);
+ name.delete(0, pos);
+ return hostname;
+ }
+
+ /**
+ * Extracts the port from a URI.
+ * @param name string buffer with the "scheme://[userinfo@]hostname" part has been removed already.
+ * Will be modified.
+ * @param uri full URI for error reporting.
+ * @return The port, or -1 if the URI does not contain a port.
+ * @throws FileSystemException if URI is malformed.
+ * @throws NumberFormatException if port number cannot be parsed.
+ */
+ protected int extractPort(final StringBuilder name, final String uri) throws FileSystemException
+ {
+ if (name.length() < 1 || name.charAt(0) != ':')
+ {
+ return -1;
+ }
+
+ final int maxlen = name.length();
+ int pos = 1;
+ for (; pos < maxlen; pos++)
+ {
+ final char ch = name.charAt(pos);
+ if (ch < '0' || ch > '9')
+ {
+ break;
+ }
+ }
+
+ final String port = name.substring(1, pos);
+ name.delete(0, pos);
+ if (port.length() == 0)
+ {
+ throw new FileSystemException("vfs.provider/missing-port.error", uri);
+ }
+
+ return Integer.parseInt(port);
+ }
+
+ /**
+ * Parsed authority info (scheme, hostname, username/password, port).
+ */
+ protected static class Authority
+ {
+ private String scheme;
+ private String hostName;
+ private String userName;
+ private String password;
+ private int port;
+
+ /**
+ * Get the connection schema.
+ * @return the connection scheme.
+ * @since 2.0
+ */
+ public String getScheme()
+ {
+ return scheme;
+ }
+
+ /**
+ * Set the connection schema.
+ * @param scheme the connection scheme.
+ * @since 2.0
+ */
+ public void setScheme(final String scheme)
+ {
+ this.scheme = scheme;
+ }
+
+ /**
+ * Get the host name.
+ * @return the host name.
+ * @since 2.0
+ */
+ public String getHostName()
+ {
+ return hostName;
+ }
+
+ /**
+ * Set the host name.
+ * @param hostName the host name.
+ * @since 2.0
+ */
+ public void setHostName(final String hostName)
+ {
+ this.hostName = hostName;
+ }
+
+ /**
+ * Get the user name.
+ * @return the user name or null.
+ * @since 2.0
+ */
+ public String getUserName()
+ {
+ return userName;
+ }
+
+ /**
+ * Set the user name.
+ * @param userName the user name.
+ * @since 2.0
+ */
+ public void setUserName(final String userName)
+ {
+ this.userName = userName;
+ }
+
+ /**
+ * Get the user password.
+ * @return the password or null.
+ * @since 2.0
+ */
+ public String getPassword()
+ {
+ return password;
+ }
+
+ /**
+ * Set the user password.
+ * @param password the user password.
+ * @since 2.0
+ */
+ public void setPassword(final String password)
+ {
+ this.password = password;
+ }
+
+ /**
+ * Get the port.
+ * @return the port or -1.
+ * @since 2.0
+ */
+ public int getPort()
+ {
+ return port;
+ }
+
+ /**
+ * Set the connection port.
+ * @param port the port number or -1.
+ * @since 2.0
+ */
+ public void setPort(final int port)
+ {
+ this.port = port;
+ }
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/LayeredFileName.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/LayeredFileName.java
new file mode 100644
index 0000000..59f474c
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/LayeredFileName.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileType;
+
+/**
+ * A file name for layered files.
+ */
+public class LayeredFileName extends AbstractFileName
+{
+ private final FileName outerUri;
+
+ public LayeredFileName(final String scheme,
+ final FileName outerUri,
+ final String path,
+ final FileType type)
+ {
+ super(scheme, path, type);
+ this.outerUri = outerUri;
+ }
+
+ /**
+ * Returns the URI of the outer file.
+ * @return The FileName.
+ */
+ public FileName getOuterName()
+ {
+ return outerUri;
+ }
+
+ /**
+ * Create a FileName.
+ * @param path The file URI.
+ * @param type The FileType.
+ * @return The FileName.
+ */
+ @Override
+ public FileName createName(final String path, final FileType type)
+ {
+ return new LayeredFileName(getScheme(), getOuterName(), path, type);
+ }
+
+ @Override
+ protected void appendRootUri(final StringBuilder buffer, final boolean addPassword)
+ {
+ buffer.append(getScheme());
+ buffer.append(":");
+ buffer.append(getOuterName().getURI());
+ buffer.append("!");
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/LayeredFileNameParser.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/LayeredFileNameParser.java
new file mode 100644
index 0000000..c735d79
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/LayeredFileNameParser.java
@@ -0,0 +1,124 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+
+/**
+ * Implementation for layered filesystems.
+ * <p>
+ * Additionally encodes the '!' character.
+ */
+public class LayeredFileNameParser extends AbstractFileNameParser
+{
+ private static final LayeredFileNameParser INSTANCE = new LayeredFileNameParser();
+
+ /**
+ * Return the Parser.
+ * @return The Parser.
+ */
+ public static LayeredFileNameParser getInstance()
+ {
+ return INSTANCE;
+ }
+
+ /**
+ * Determines if a character should be encoded.
+ * @param ch The character to check.
+ * @return true if the character should be encoded.
+ */
+ @Override
+ public boolean encodeCharacter(final char ch)
+ {
+ return super.encodeCharacter(ch) || ch == '!';
+ }
+
+ /**
+ * Parse the base and name into a FileName.
+ * @param context The component context.
+ * @param base The base FileName.
+ * @param filename The target file name.
+ * @return The constructed FileName.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileName parseUri(final VfsComponentContext context, final FileName base, final String filename)
+ throws FileSystemException
+ {
+ final StringBuilder name = new StringBuilder();
+
+ // Extract the scheme
+ final String scheme = UriParser.extractScheme(filename, name);
+
+ // Extract the Layered file URI
+ final String rootUriName = extractRootName(name);
+ FileName rootUri = null;
+ if (rootUriName != null)
+ {
+ rootUri = context.parseURI(rootUriName);
+ }
+
+ // Decode and normalise the path
+ UriParser.canonicalizePath(name, 0, name.length(), this);
+ UriParser.fixSeparators(name);
+ final FileType fileType = UriParser.normalisePath(name);
+ final String path = name.toString();
+
+ return new LayeredFileName(scheme, rootUri, path, fileType);
+ }
+
+ /**
+ * Pops the root prefix off a URI, which has had the scheme removed.
+ *
+ * @param uri string builder which gets modified.
+ * @return the extracted root name.
+ * @throws FileSystemException if error occurs.
+ */
+ protected String extractRootName(final StringBuilder uri)
+ throws FileSystemException
+ {
+ // Looking for <name>!<abspath> (staring at the end)
+ final int maxlen = uri.length();
+ int pos = maxlen - 1;
+ for (; pos > 0 && uri.charAt(pos) != '!'; pos--)
+ {
+ }
+
+ if (pos == 0 && uri.charAt(pos) != '!')
+ {
+ // not ! found, so take the whole path a root
+ // e.g. zip:/my/zip/file.zip
+ pos = maxlen;
+ }
+
+ // Extract the name
+ final String prefix = uri.substring(0, pos);
+ if (pos < maxlen)
+ {
+ uri.delete(0, pos + 1);
+ }
+ else
+ {
+ uri.setLength(0);
+ }
+
+ return prefix;
+ }
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/LocalFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/LocalFileProvider.java
new file mode 100644
index 0000000..5387ebe
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/LocalFileProvider.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import java.io.File;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+
+/**
+ * A file provider which handles local files.
+ */
+public interface LocalFileProvider
+ extends FileProvider
+{
+ /**
+ * Determines if a name is an absolute file name.
+ * <p>
+ * TODO - Move this to a general file name parser interface.
+ *
+ * @param name The name to test.
+ * @return true if the name is absolute.
+ */
+ boolean isAbsoluteLocalName(final String name);
+
+ /**
+ * Finds a local file, from its local name.
+ * @param name The name of the file to locate.
+ * @return The FileObject for the file.
+ * @throws FileSystemException if an error occurs.
+ */
+ FileObject findLocalFile(final String name)
+ throws FileSystemException;
+
+ /**
+ * Converts from java.io.File to FileObject.
+ * @param file The File for the file.
+ * @return The FileObject for the file.
+ * @throws FileSystemException if an error occurs.
+ */
+ FileObject findLocalFile(final File file)
+ throws FileSystemException;
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/TemporaryFileStore.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/TemporaryFileStore.java
new file mode 100644
index 0000000..b68d839
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/TemporaryFileStore.java
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import java.io.File;
+
+import org.apache.commons.vfs2.FileSystemException;
+
+/**
+ * Manages a repository of temporary local files.
+ */
+public interface TemporaryFileStore
+{
+ /**
+ * Allocates a new temporary file. The file (and all its descendants)
+ * will be deleted when this store is closed.
+ *
+ * @param basename The name of the file.
+ * @return The temporary file.
+ * @throws FileSystemException if an error occurs.
+ */
+ File allocateFile(String basename) throws FileSystemException;
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/URLFileName.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/URLFileName.java
new file mode 100644
index 0000000..1ad17e5
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/URLFileName.java
@@ -0,0 +1,164 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import org.apache.commons.httpclient.URIException;
+import org.apache.commons.httpclient.util.URIUtil;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+
+/**
+ * A file name that represents URL.
+ */
+public class URLFileName extends GenericFileName
+{
+ private static final int BUFFER_SIZE = 250;
+
+ private final String queryString;
+
+ public URLFileName(final String scheme,
+ final String hostName,
+ final int port,
+ final int defaultPort,
+ final String userName,
+ final String password,
+ final String path,
+ final FileType type,
+ final String queryString)
+ {
+ super(scheme, hostName, port, defaultPort, userName, password, path, type);
+ this.queryString = queryString;
+ }
+
+ /**
+ * Get the query string.
+ *
+ * @return the query string part of the filename
+ */
+ public String getQueryString()
+ {
+ return queryString;
+ }
+
+ /**
+ * Get the path and query string e.g. /path/servlet?param1=true.
+ *
+ * @return the path and its query string
+ */
+ public String getPathQuery()
+ {
+ final StringBuilder sb = new StringBuilder(BUFFER_SIZE);
+ sb.append(getPath());
+ sb.append("?");
+ sb.append(getQueryString());
+
+ return sb.toString();
+ }
+
+ /**
+ * Get the path encoded suitable for url like filesystem e.g. (http, webdav).
+ *
+ * @param charset the charset used for the path encoding
+ * @return The encoded path.
+ * @throws URIException If an error occurs encoding the URI.
+ * @throws FileSystemException If some other error occurs.
+ */
+ public String getPathQueryEncoded(final String charset) throws URIException, FileSystemException
+ {
+ if (getQueryString() == null)
+ {
+ if (charset != null)
+ {
+ return URIUtil.encodePath(getPathDecoded(), charset);
+ }
+ else
+ {
+ return URIUtil.encodePath(getPathDecoded());
+ }
+ }
+
+ final StringBuilder sb = new StringBuilder(BUFFER_SIZE);
+ if (charset != null)
+ {
+ sb.append(URIUtil.encodePath(getPathDecoded(), charset));
+ }
+ else
+ {
+ sb.append(URIUtil.encodePath(getPathDecoded()));
+ }
+ sb.append("?");
+ sb.append(getQueryString());
+ return sb.toString();
+ }
+
+ /**
+ * Create a FileName.
+ * @param absPath The absolute path.
+ * @param type The FileType.
+ * @return The FileName
+ */
+ @Override
+ public FileName createName(final String absPath, final FileType type)
+ {
+ return new URLFileName(getScheme(),
+ getHostName(),
+ getPort(),
+ getDefaultPort(),
+ getUserName(),
+ getPassword(),
+ absPath,
+ type,
+ getQueryString());
+ }
+
+ /**
+ * Append query string to the uri.
+ *
+ * @return the uri
+ */
+ @Override
+ protected String createURI()
+ {
+ if (getQueryString() != null)
+ {
+ final StringBuilder sb = new StringBuilder(BUFFER_SIZE);
+ sb.append(super.createURI());
+ sb.append("?");
+ sb.append(getQueryString());
+
+ return sb.toString();
+ }
+
+ return super.createURI();
+ }
+
+ /**
+ * Encode a URI.
+ * @param charset The character set.
+ * @return The encoded URI
+ * @throws FileSystemException if some other exception occurs.
+ * @throws URIException if an exception occurs encoding the URI.
+ */
+ public String getURIEncoded(final String charset) throws FileSystemException, URIException
+ {
+ final StringBuilder sb = new StringBuilder(BUFFER_SIZE);
+ appendRootUri(sb, true);
+ sb.append(getPathQueryEncoded(charset));
+ return sb.toString();
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/URLFileNameParser.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/URLFileNameParser.java
new file mode 100644
index 0000000..c6d2803
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/URLFileNameParser.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+
+/**
+ * Implementation for any url based filesystem.
+ * <p>
+ * Parses the url into user/password/host/port/path/queryString.
+ */
+public class URLFileNameParser extends HostFileNameParser
+{
+ public URLFileNameParser(final int defaultPort)
+ {
+ super(defaultPort);
+ }
+
+ @Override
+ public boolean encodeCharacter(final char ch)
+ {
+ return super.encodeCharacter(ch) || ch == '?';
+ }
+
+ @Override
+ public FileName parseUri(final VfsComponentContext context, final FileName base, final String filename)
+ throws FileSystemException
+ {
+ // FTP URI are generic URI (as per RFC 2396)
+ final StringBuilder name = new StringBuilder();
+
+ // Extract the scheme and authority parts
+ final Authority auth = extractToPath(filename, name);
+
+ // Extract the queryString
+ final String queryString = UriParser.extractQueryString(name);
+
+ // Decode and normalise the file name
+ UriParser.canonicalizePath(name, 0, name.length(), this);
+ UriParser.fixSeparators(name);
+ final FileType fileType = UriParser.normalisePath(name);
+ final String path = name.toString();
+
+ return new URLFileName(
+ auth.getScheme(),
+ auth.getHostName(),
+ auth.getPort(),
+ getDefaultPort(),
+ auth.getUserName(),
+ auth.getPassword(),
+ path,
+ fileType,
+ queryString);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/UriParser.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/UriParser.java
new file mode 100644
index 0000000..ef0ba84
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/UriParser.java
@@ -0,0 +1,536 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.VFS;
+import org.apache.commons.vfs2.util.Os;
+
+/**
+ * Utilities for dealing with URIs. See RFC 2396 for details.
+ *
+ * 2005) $
+ */
+public final class UriParser
+{
+ /**
+ * The set of valid separators. These are all converted to the normalized
+ * one. Does <i>not</i> contain the normalized separator
+ */
+ // public static final char[] separators = {'\\'};
+ public static final char TRANS_SEPARATOR = '\\';
+
+ /**
+ * The normalised separator to use.
+ */
+ private static final char SEPARATOR_CHAR = FileName.SEPARATOR_CHAR;
+
+ private static final int HEX_BASE = 16;
+
+ private static final int BITS_IN_HALF_BYTE = 4;
+
+ private static final char LOW_MASK = 0x0F;
+
+ private UriParser()
+ {
+ }
+
+ /**
+ * Extracts the first element of a path.
+ * @param name StringBuilder containing the path.
+ * @return The first element of the path.
+ */
+ public static String extractFirstElement(final StringBuilder name)
+ {
+ final int len = name.length();
+ if (len < 1)
+ {
+ return null;
+ }
+ int startPos = 0;
+ if (name.charAt(0) == SEPARATOR_CHAR)
+ {
+ startPos = 1;
+ }
+ for (int pos = startPos; pos < len; pos++)
+ {
+ if (name.charAt(pos) == SEPARATOR_CHAR)
+ {
+ // Found a separator
+ final String elem = name.substring(startPos, pos);
+ name.delete(startPos, pos + 1);
+ return elem;
+ }
+ }
+
+ // No separator
+ final String elem = name.substring(startPos);
+ name.setLength(0);
+ return elem;
+ }
+
+ /**
+ * Normalises a path. Does the following:
+ * <ul>
+ * <li>Removes empty path elements.
+ * <li>Handles '.' and '..' elements.
+ * <li>Removes trailing separator.
+ * </ul>
+ *
+ * Its assumed that the separators are already fixed.
+ *
+ * @param path The path to normalize.
+ * @return The FileType.
+ * @throws FileSystemException if an error occurs.
+ *
+ * @see #fixSeparators
+ */
+ public static FileType normalisePath(final StringBuilder path)
+ throws FileSystemException
+ {
+ FileType fileType = FileType.FOLDER;
+ if (path.length() == 0)
+ {
+ return fileType;
+ }
+
+ if (path.charAt(path.length() - 1) != '/')
+ {
+ fileType = FileType.FILE;
+ }
+
+ // Adjust separators
+ // fixSeparators(path);
+
+ // Determine the start of the first element
+ int startFirstElem = 0;
+ if (path.charAt(0) == SEPARATOR_CHAR)
+ {
+ if (path.length() == 1)
+ {
+ return fileType;
+ }
+ startFirstElem = 1;
+ }
+
+ // Iterate over each element
+ int startElem = startFirstElem;
+ int maxlen = path.length();
+ while (startElem < maxlen)
+ {
+ // Find the end of the element
+ int endElem = startElem;
+ for (; endElem < maxlen && path.charAt(endElem) != SEPARATOR_CHAR; endElem++)
+ {
+ }
+
+ final int elemLen = endElem - startElem;
+ if (elemLen == 0)
+ {
+ // An empty element - axe it
+ path.delete(endElem, endElem + 1);
+ maxlen = path.length();
+ continue;
+ }
+ if (elemLen == 1 && path.charAt(startElem) == '.')
+ {
+ // A '.' element - axe it
+ path.delete(startElem, endElem + 1);
+ maxlen = path.length();
+ continue;
+ }
+ if (elemLen == 2 && path.charAt(startElem) == '.'
+ && path.charAt(startElem + 1) == '.')
+ {
+ // A '..' element - remove the previous element
+ if (startElem == startFirstElem)
+ {
+ // Previous element is missing
+ throw new FileSystemException(
+ "vfs.provider/invalid-relative-path.error");
+ }
+
+ // Find start of previous element
+ int pos = startElem - 2;
+ for (; pos >= 0 && path.charAt(pos) != SEPARATOR_CHAR; pos--)
+ {
+ }
+ startElem = pos + 1;
+
+ path.delete(startElem, endElem + 1);
+ maxlen = path.length();
+ continue;
+ }
+
+ // A regular element
+ startElem = endElem + 1;
+ }
+
+ // Remove trailing separator
+ if (!VFS.isUriStyle() && maxlen > 1 && path.charAt(maxlen - 1) == SEPARATOR_CHAR)
+ {
+ path.delete(maxlen - 1, maxlen);
+ }
+
+ return fileType;
+ }
+
+ /**
+ * Normalises the separators in a name.
+ * @param name The StringBuilder containing the name
+ * @return true if the StringBuilder was modified.
+ */
+ public static boolean fixSeparators(final StringBuilder name)
+ {
+ boolean changed = false;
+ final int maxlen = name.length();
+ for (int i = 0; i < maxlen; i++)
+ {
+ final char ch = name.charAt(i);
+ if (ch == TRANS_SEPARATOR)
+ {
+ name.setCharAt(i, SEPARATOR_CHAR);
+ changed = true;
+ }
+ }
+ return changed;
+ }
+
+ /**
+ * Extracts the scheme from a URI.
+ *
+ * @param uri The URI.
+ * @return The scheme name. Returns null if there is no scheme.
+ */
+ public static String extractScheme(final String uri)
+ {
+ return extractScheme(uri, null);
+ }
+
+ /**
+ * Extracts the scheme from a URI. Removes the scheme and ':' delimiter from
+ * the front of the URI.
+ *
+ * @param uri The URI.
+ * @param buffer Returns the remainder of the URI.
+ * @return The scheme name. Returns null if there is no scheme.
+ */
+ public static String extractScheme(final String uri, final StringBuilder buffer)
+ {
+ if (buffer != null)
+ {
+ buffer.setLength(0);
+ buffer.append(uri);
+ }
+
+ final int maxPos = uri.length();
+ for (int pos = 0; pos < maxPos; pos++)
+ {
+ final char ch = uri.charAt(pos);
+
+ if (ch == ':')
+ {
+ // Found the end of the scheme
+ final String scheme = uri.substring(0, pos);
+ if (scheme.length() <= 1 && Os.isFamily(Os.OS_FAMILY_WINDOWS))
+ {
+ // This is not a scheme, but a Windows drive letter
+ return null;
+ }
+ if (buffer != null)
+ {
+ buffer.delete(0, pos + 1);
+ }
+ return scheme.intern();
+ }
+
+ if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
+ {
+ // A scheme character
+ continue;
+ }
+ if (pos > 0
+ && ((ch >= '0' && ch <= '9') || ch == '+' || ch == '-' || ch == '.'))
+ {
+ // A scheme character (these are not allowed as the first
+ // character of the scheme, but can be used as subsequent
+ // characters.
+ continue;
+ }
+
+ // Not a scheme character
+ break;
+ }
+
+ // No scheme in URI
+ return null;
+ }
+
+ /**
+ * Removes %nn encodings from a string.
+ * @param encodedStr The encoded String.
+ * @return The decoded String.
+ * @throws FileSystemException if an error occurs.
+ */
+ public static String decode(final String encodedStr)
+ throws FileSystemException
+ {
+ if (encodedStr == null)
+ {
+ return null;
+ }
+ if (encodedStr.indexOf('%') < 0)
+ {
+ return encodedStr;
+ }
+ final StringBuilder buffer = new StringBuilder(encodedStr);
+ decode(buffer, 0, buffer.length());
+ return buffer.toString();
+ }
+
+ /**
+ * Removes %nn encodings from a string.
+ * @param buffer StringBuilder containing the string to decode.
+ * @param offset The position in the string to start decoding.
+ * @param length The number of characters to decode.
+ * @throws FileSystemException if an error occurs.
+ */
+ public static void decode(final StringBuilder buffer, final int offset, final int length)
+ throws FileSystemException
+ {
+ int index = offset;
+ int count = length;
+ for (; count > 0; count--, index++)
+ {
+ final char ch = buffer.charAt(index);
+ if (ch != '%')
+ {
+ continue;
+ }
+ if (count < 3)
+ {
+ throw new FileSystemException(
+ "vfs.provider/invalid-escape-sequence.error", buffer
+ .substring(index, index + count));
+ }
+
+ // Decode
+ final int dig1 = Character.digit(buffer.charAt(index + 1), HEX_BASE);
+ final int dig2 = Character.digit(buffer.charAt(index + 2), HEX_BASE);
+ if (dig1 == -1 || dig2 == -1)
+ {
+ throw new FileSystemException(
+ "vfs.provider/invalid-escape-sequence.error", buffer
+ .substring(index, index + 3));
+ }
+ final char value = (char) (dig1 << BITS_IN_HALF_BYTE | dig2);
+
+ // Replace
+ buffer.setCharAt(index, value);
+ buffer.delete(index + 1, index + 3);
+ count -= 2;
+ }
+ }
+
+ /**
+ * Encodes and appends a string to a StringBuilder.
+ * @param buffer The StringBuilder to append to.
+ * @param unencodedValue The String to encode and append.
+ * @param reserved characters to encode.
+ */
+ public static void appendEncoded(final StringBuilder buffer,
+ final String unencodedValue, final char[] reserved)
+ {
+ final int offset = buffer.length();
+ buffer.append(unencodedValue);
+ encode(buffer, offset, unencodedValue.length(), reserved);
+ }
+
+ /**
+ * Encodes a set of reserved characters in a StringBuilder, using the URI %nn
+ * encoding. Always encodes % characters.
+ * @param buffer The StringBuilder to append to.
+ * @param offset The position in the buffer to start encoding at.
+ * @param length The number of characters to encode.
+ * @param reserved characters to encode.
+ */
+ public static void encode(final StringBuilder buffer, final int offset,
+ final int length, final char[] reserved)
+ {
+ int index = offset;
+ int count = length;
+ for (; count > 0; index++, count--)
+ {
+ final char ch = buffer.charAt(index);
+ boolean match = ch == '%';
+ if (reserved != null)
+ {
+ for (int i = 0; !match && i < reserved.length; i++)
+ {
+ if (ch == reserved[i])
+ {
+ match = true;
+ }
+ }
+ }
+ if (match)
+ {
+ // Encode
+ final char[] digits =
+ {Character.forDigit((ch >> BITS_IN_HALF_BYTE) & LOW_MASK, HEX_BASE),
+ Character.forDigit(ch & LOW_MASK, HEX_BASE)};
+ buffer.setCharAt(index, '%');
+ buffer.insert(index + 1, digits);
+ index += 2;
+ }
+ }
+ }
+
+ /**
+ * Removes %nn encodings from a string.
+ * @param decodedStr The decoded String.
+ * @return The encoded String.
+ */
+ public static String encode(final String decodedStr)
+ {
+ return encode(decodedStr, null);
+ }
+
+ /**
+ * Converts "special" characters to their %nn value.
+ * @param decodedStr The decoded String.
+ * @param reserved Characters to encode.
+ * @return The encoded String
+ */
+ public static String encode(final String decodedStr, final char[] reserved)
+ {
+ if (decodedStr == null)
+ {
+ return null;
+ }
+ final StringBuilder buffer = new StringBuilder(decodedStr);
+ encode(buffer, 0, buffer.length(), reserved);
+ return buffer.toString();
+ }
+
+ /**
+ * Encode an array of Strings.
+ * @param strings The array of Strings to encode.
+ * @return An array of encoded Strings.
+ */
+ public static String[] encode(final String[] strings)
+ {
+ if (strings == null)
+ {
+ return null;
+ }
+ for (int i = 0; i < strings.length; i++)
+ {
+ strings[i] = encode(strings[i]);
+ }
+ return strings;
+ }
+
+ /**
+ * Decodes the String.
+ * @param uri The String to decode.
+ * @throws FileSystemException if an error occurs.
+ */
+ public static void checkUriEncoding(final String uri) throws FileSystemException
+ {
+ decode(uri);
+ }
+
+ public static void canonicalizePath(final StringBuilder buffer, final int offset,
+ final int length, final FileNameParser fileNameParser)
+ throws FileSystemException
+ {
+ int index = offset;
+ int count = length;
+ for (; count > 0; count--, index++)
+ {
+ final char ch = buffer.charAt(index);
+ if (ch == '%')
+ {
+ if (count < 3)
+ {
+ throw new FileSystemException(
+ "vfs.provider/invalid-escape-sequence.error",
+ buffer.substring(index, index + count));
+ }
+
+ // Decode
+ final int dig1 = Character.digit(buffer.charAt(index + 1), HEX_BASE);
+ final int dig2 = Character.digit(buffer.charAt(index + 2), HEX_BASE);
+ if (dig1 == -1 || dig2 == -1)
+ {
+ throw new FileSystemException(
+ "vfs.provider/invalid-escape-sequence.error",
+ buffer.substring(index, index + 3));
+ }
+ final char value = (char) (dig1 << BITS_IN_HALF_BYTE | dig2);
+
+ final boolean match = value == '%' || fileNameParser.encodeCharacter(value);
+
+ if (match)
+ {
+ // this is a reserved character, not allowed to decode
+ index += 2;
+ count -= 2;
+ continue;
+ }
+
+ // Replace
+ buffer.setCharAt(index, value);
+ buffer.delete(index + 1, index + 3);
+ count -= 2;
+ }
+ else if (fileNameParser.encodeCharacter(ch))
+ {
+ // Encode
+ final char[] digits =
+ {Character.forDigit((ch >> BITS_IN_HALF_BYTE) & LOW_MASK, HEX_BASE),
+ Character.forDigit(ch & LOW_MASK, HEX_BASE)};
+ buffer.setCharAt(index, '%');
+ buffer.insert(index + 1, digits);
+ index += 2;
+ }
+ }
+ }
+
+ /**
+ * Extract the query String from the URI.
+ * @param name StringBuilder containing the URI.
+ * @return The query string, if any. null otherwise.
+ */
+ public static String extractQueryString(final StringBuilder name)
+ {
+ for (int pos = 0; pos < name.length(); pos++)
+ {
+ if (name.charAt(pos) == '?')
+ {
+ final String queryString = name.substring(pos + 1);
+ name.delete(pos, name.length());
+ return queryString;
+ }
+ }
+
+ return null;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/VfsComponent.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/VfsComponent.java
new file mode 100644
index 0000000..0740f4b
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/VfsComponent.java
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.vfs2.FileSystemException;
+
+/**
+ * This interface is used to manage the lifecycle of all VFS components.
+ * This includes all implementations of the following interfaces:
+ * <ul>
+ * <li>{@link FileProvider}
+ * <li>{@link org.apache.commons.vfs2.FileSystem}
+ * <li>{@link FileReplicator}
+ * <li>{@link TemporaryFileStore}
+ * </ul>
+ */
+public interface VfsComponent
+{
+ /**
+ * Sets the Logger to use for the component.
+ *
+ * @param logger The Log
+ */
+ void setLogger(Log logger);
+
+ /**
+ * Sets the context for the component.
+ *
+ * @param context The context.
+ */
+ void setContext(VfsComponentContext context);
+
+ /**
+ * Initializes the component.
+ * @throws FileSystemException if an error occurs.
+ */
+ void init() throws FileSystemException;
+
+ /**
+ * Closes the component.
+ */
+ void close();
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/VfsComponentContext.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/VfsComponentContext.java
new file mode 100644
index 0000000..82ffb60
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/VfsComponentContext.java
@@ -0,0 +1,97 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import java.io.File;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FileSystemOptions;
+
+/**
+ * Allows VFS components to access the services they need, such as the file
+ * replicator. A VFS component is supplied with a context as part of its
+ * initialisation.
+ *
+ * @see VfsComponent#setContext
+ */
+public interface VfsComponentContext
+{
+ /**
+ * Locate a file by name. See
+ * {@link FileSystemManager#resolveFile(FileObject, String)} for a
+ * description of how this works.
+ * @param baseFile The base FileObject.
+ * @param name The name of the file to locate.
+ * @param fileSystemOptions The FileSystemOptions.
+ * @return The FileObject for the located file.
+ * @throws FileSystemException if an error occurs.
+ */
+ FileObject resolveFile(FileObject baseFile, String name, FileSystemOptions fileSystemOptions)
+ throws FileSystemException;
+
+ /**
+ * Locate a file by name. See
+ * {@link FileSystemManager#resolveFile( String)} for a
+ * description of how this works.
+ * @param name The name of the file to locate.
+ * @param fileSystemOptions The FileSystemOptions.
+ * @return The FileObject for the located file.
+ * @throws FileSystemException if an error occurs.
+ */
+ FileObject resolveFile(String name, FileSystemOptions fileSystemOptions)
+ throws FileSystemException;
+
+ /**
+ * Parse a URI into a FileName.
+ * @param uri The URI String.
+ * @return The FileName.
+ * @throws FileSystemException if an error occurs.
+ */
+ FileName parseURI(String uri) throws FileSystemException;
+
+ /**
+ * Locates a file replicator for the provider to use.
+ * @return The FileReplicator.
+ * @throws FileSystemException if an error occurs.
+ */
+ FileReplicator getReplicator() throws FileSystemException;
+
+ /**
+ * Locates a temporary file store for the provider to use.
+ * @return The TemporaryFileStore.
+ * @throws FileSystemException if an error occurs.
+ */
+ TemporaryFileStore getTemporaryFileStore() throws FileSystemException;
+
+ /**
+ * Returns a {@link FileObject} for a local file.
+ * @param file The File to convert to a FileObject.
+ * @return the FileObject.
+ * @throws FileSystemException if an error occurs.
+ */
+ FileObject toFileObject(File file) throws FileSystemException;
+
+ /**
+ * Returns the filesystem manager for the current context.
+ *
+ * @return the filesystem manager
+ */
+ FileSystemManager getFileSystemManager();
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/bzip2/Bzip2FileObject.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/bzip2/Bzip2FileObject.java
new file mode 100644
index 0000000..8071414
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/bzip2/Bzip2FileObject.java
@@ -0,0 +1,77 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.bzip2;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import org.apache.commons.compress.compressors.bzip2.BZip2CompressorInputStream;
+import org.apache.commons.compress.compressors.bzip2.BZip2CompressorOutputStream;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.compressed.CompressedFileFileObject;
+import org.apache.commons.vfs2.provider.compressed.CompressedFileFileSystem;
+
+/**
+ * the bzip2 file.
+ */
+public class Bzip2FileObject extends CompressedFileFileObject<Bzip2FileSystem>
+{
+ /**
+ * Deprecated since 2.1.
+ *
+ * @deprecated Use {@link #Bzip2FileObject(AbstractFileName, FileObject, Bzip2FileSystem)} instead.
+ */
+ @Deprecated
+ protected Bzip2FileObject(final AbstractFileName name, final FileObject container, final CompressedFileFileSystem fs)
+ {
+ super(name, container, cast(fs));
+ }
+
+ protected Bzip2FileObject(final AbstractFileName name, final FileObject container, final Bzip2FileSystem fs)
+ {
+ super(name, container, fs);
+ }
+
+ @Override
+ protected InputStream doGetInputStream() throws Exception
+ {
+ // check file
+ final InputStream is = getContainer().getContent().getInputStream();
+ return wrapInputStream(getName().getURI(), is);
+ }
+
+ public static InputStream wrapInputStream(final String name, final InputStream is) throws IOException
+ {
+ return new BZip2CompressorInputStream(is);
+ }
+
+ @Override
+ protected OutputStream doGetOutputStream(final boolean bAppend) throws Exception
+ {
+ final OutputStream os = getContainer().getContent().getOutputStream(false);
+ return new BZip2CompressorOutputStream(os);
+ }
+
+ private static Bzip2FileSystem cast(CompressedFileFileSystem fs) {
+ if (fs instanceof Bzip2FileSystem) {
+ return (Bzip2FileSystem) fs;
+ }
+ throw new IllegalArgumentException("Bzip2FileObject requires a Bzip2FileSystem implementation");
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/bzip2/Bzip2FileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/bzip2/Bzip2FileProvider.java
new file mode 100644
index 0000000..84ec23b
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/bzip2/Bzip2FileProvider.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.bzip2;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.compressed.CompressedFileFileProvider;
+
+/**
+ * Provides access to the content of bzip2 compressed files.
+ */
+public class Bzip2FileProvider extends CompressedFileFileProvider
+{
+ /** The provider's capabilities */
+ protected static final Collection<Capability> capabilities =
+ Collections.unmodifiableCollection(Arrays.asList(new Capability[]
+ {
+ Capability.GET_LAST_MODIFIED,
+ Capability.GET_TYPE,
+ Capability.LIST_CHILDREN,
+ Capability.READ_CONTENT,
+ Capability.WRITE_CONTENT,
+ Capability.URI,
+ Capability.COMPRESS
+ }));
+
+ public Bzip2FileProvider()
+ {
+ super();
+ }
+
+ @Override
+ protected FileSystem createFileSystem(final FileName name, final FileObject file,
+ final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ return new Bzip2FileSystem(name, file, fileSystemOptions);
+ }
+
+ @Override
+ public Collection<Capability> getCapabilities()
+ {
+ return capabilities;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/bzip2/Bzip2FileSystem.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/bzip2/Bzip2FileSystem.java
new file mode 100644
index 0000000..4c99003
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/bzip2/Bzip2FileSystem.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.bzip2;
+
+import java.util.Collection;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.compressed.CompressedFileFileSystem;
+
+/**
+ * Filesytem to handle compressed files using the bzip2 method.
+ */
+public class Bzip2FileSystem extends CompressedFileFileSystem
+{
+ protected Bzip2FileSystem(final FileName rootName, final FileObject parentLayer,
+ final FileSystemOptions fileSystemOptions)
+ {
+ super(rootName, parentLayer, fileSystemOptions);
+ }
+
+ @Override
+ protected FileObject createFile(final AbstractFileName name) throws FileSystemException
+ {
+ return new Bzip2FileObject(name, getParentLayer(), this);
+ }
+
+ @Override
+ protected void addCapabilities(final Collection<Capability> caps)
+ {
+ caps.addAll(Bzip2FileProvider.capabilities);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/bzip2/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/bzip2/package.html
new file mode 100644
index 0000000..f794b5c
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/bzip2/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>The BZIP2 File Provider</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/compressed/CompressedFileFileObject.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/compressed/CompressedFileFileObject.java
new file mode 100644
index 0000000..36c93aa
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/compressed/CompressedFileFileObject.java
@@ -0,0 +1,123 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.compressed;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileObject;
+
+/**
+ * A compressed file.
+ *
+ * <p>
+ * Such a file only has one child (the compressed filename with stripped last extension)
+ * </p>
+ *
+ * @param <FS>
+ * A CompressedFileFileSystem
+ */
+public abstract class CompressedFileFileObject<FS extends CompressedFileFileSystem> extends AbstractFileObject<FS>
+{
+ private final FileObject container;
+ private final String[] children;
+
+ protected CompressedFileFileObject(final AbstractFileName name, final FileObject container, final FS fs)
+ {
+ super(name, fs);
+ this.container = container;
+
+ // todo, add getBaseName(String) to FileName
+ String basename = container.getName().getBaseName();
+ final int pos = basename.lastIndexOf('.');
+ if (pos > 0)
+ {
+ basename = basename.substring(0, pos);
+ }
+ children = new String[]{basename};
+ }
+
+ /**
+ * Determines if this file can be written to.
+ *
+ * @return {@code true} if this file is writeable, {@code false} if not.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public boolean isWriteable() throws FileSystemException
+ {
+ return getFileSystem().hasCapability(Capability.WRITE_CONTENT);
+ }
+
+ /**
+ * Returns the file's type.
+ */
+ @Override
+ protected FileType doGetType() throws FileSystemException
+ {
+ if (getName().getPath().endsWith("/"))
+ {
+ return FileType.FOLDER;
+ }
+ else
+ {
+ return FileType.FILE;
+ }
+ }
+
+ /**
+ * Lists the children of the file.
+ */
+ @Override
+ protected String[] doListChildren()
+ {
+ return children;
+ }
+
+ /**
+ * Returns the size of the file content (in bytes). Is only called if
+ * {@link #doGetType} returns {@link FileType#FILE}.
+ */
+ @Override
+ protected long doGetContentSize()
+ {
+ return -1;
+ }
+
+ /**
+ * Returns the last modified time of this file.
+ */
+ @Override
+ protected long doGetLastModifiedTime() throws Exception
+ {
+ return container.getContent().getLastModifiedTime();
+ }
+
+ protected FileObject getContainer()
+ {
+ return container;
+ }
+
+ @Override
+ public void createFile() throws FileSystemException
+ {
+ container.createFile();
+ injectType(FileType.FILE);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/compressed/CompressedFileFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/compressed/CompressedFileFileProvider.java
new file mode 100644
index 0000000..6a451e9
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/compressed/CompressedFileFileProvider.java
@@ -0,0 +1,83 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.compressed;
+
+import java.util.Collection;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.provider.AbstractLayeredFileProvider;
+import org.apache.commons.vfs2.provider.FileProvider;
+import org.apache.commons.vfs2.provider.LayeredFileName;
+
+/**
+ * A file system provider for compressed files. Provides read-only file
+ * systems.
+ */
+public abstract class CompressedFileFileProvider
+ extends AbstractLayeredFileProvider
+ implements FileProvider
+{
+ public CompressedFileFileProvider()
+ {
+ super();
+ }
+
+ /**
+ * Parses an absolute URI.
+ *
+ * @param uri The URI to parse.
+ */
+ /*
+ public FileName parseUri(final String uri)
+ throws FileSystemException
+ {
+ return ZipFileName.parseUri(uri);
+ }
+ */
+
+ /**
+ * Creates a layered file system. This method is called if the file system
+ * is not cached.
+ *
+ * @param scheme The URI scheme.
+ * @param file The file to create the file system on top of.
+ * @return The file system.
+ */
+ @Override
+ protected FileSystem doCreateFileSystem(final String scheme,
+ final FileObject file,
+ final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ final FileName name =
+ new LayeredFileName(scheme, file.getName(), FileName.ROOT_PATH, FileType.FOLDER);
+ return createFileSystem(name, file, fileSystemOptions);
+ }
+
+ protected abstract FileSystem createFileSystem(final FileName name, final FileObject file,
+ final FileSystemOptions fileSystemOptions)
+ throws FileSystemException;
+
+ @Override
+ public abstract Collection<Capability> getCapabilities();
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/compressed/CompressedFileFileSystem.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/compressed/CompressedFileFileSystem.java
new file mode 100644
index 0000000..dca18dd
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/compressed/CompressedFileFileSystem.java
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.compressed;
+
+import java.util.Collection;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileSystem;
+
+/**
+ * A read-only file system for compressed files.
+ */
+public abstract class CompressedFileFileSystem
+ extends AbstractFileSystem
+{
+ protected CompressedFileFileSystem(final FileName rootName,
+ final FileObject parentLayer,
+ final FileSystemOptions fileSystemOptions)
+ {
+ super(rootName, parentLayer, fileSystemOptions);
+ }
+
+ /**
+ * Returns the capabilities of this file system.
+ */
+ @Override
+ protected abstract void addCapabilities(final Collection<Capability> caps);
+
+ /**
+ * Creates a file object.
+ */
+ @Override
+ protected abstract FileObject createFile(final AbstractFileName name) throws FileSystemException;
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/compressed/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/compressed/package.html
new file mode 100644
index 0000000..4c216d0
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/compressed/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>The compressed file provider</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FTPClientWrapper.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FTPClientWrapper.java
new file mode 100644
index 0000000..e73a342
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FTPClientWrapper.java
@@ -0,0 +1,344 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ftp;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.net.ftp.FTPClient;
+import org.apache.commons.net.ftp.FTPFile;
+import org.apache.commons.net.ftp.FTPReply;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.UserAuthenticationData;
+import org.apache.commons.vfs2.provider.GenericFileName;
+import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
+
+/**
+ * A wrapper to the FTPClient to allow automatic reconnect on connection loss.
+ * <p>
+ * I decided to not to use eg. noop() to determine the state of the connection to avoid
+ * unnecessary server round-trips.
+ */
+public class FTPClientWrapper implements FtpClient
+{
+
+ private static final Log LOG = LogFactory.getLog(FTPClientWrapper.class);
+
+ protected final FileSystemOptions fileSystemOptions;
+ private final GenericFileName root;
+ private FTPClient ftpClient;
+
+ protected FTPClientWrapper(final GenericFileName root, final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ this.root = root;
+ this.fileSystemOptions = fileSystemOptions;
+ getFtpClient(); // fail-fast
+ }
+
+ public GenericFileName getRoot()
+ {
+ return root;
+ }
+
+ public FileSystemOptions getFileSystemOptions()
+ {
+ return fileSystemOptions;
+ }
+
+ private FTPClient createClient() throws FileSystemException
+ {
+ final GenericFileName rootName = getRoot();
+
+ UserAuthenticationData authData = null;
+ try
+ {
+ authData = UserAuthenticatorUtils.authenticate(fileSystemOptions, FtpFileProvider.AUTHENTICATOR_TYPES);
+
+ return createClient(rootName, authData);
+ }
+ finally
+ {
+ UserAuthenticatorUtils.cleanup(authData);
+ }
+ }
+
+ protected FTPClient createClient(final GenericFileName rootName, final UserAuthenticationData authData)
+ throws FileSystemException
+ {
+ return FtpClientFactory.createConnection(
+ rootName.getHostName(),
+ rootName.getPort(),
+ UserAuthenticatorUtils.getData(
+ authData, UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(rootName.getUserName())),
+ UserAuthenticatorUtils.getData(
+ authData, UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(rootName.getPassword())),
+ rootName.getPath(), getFileSystemOptions());
+ }
+
+ private FTPClient getFtpClient() throws FileSystemException
+ {
+ if (ftpClient == null)
+ {
+ ftpClient = createClient();
+ }
+
+ return ftpClient;
+ }
+
+ @Override
+ public boolean isConnected() throws FileSystemException
+ {
+ return ftpClient != null && ftpClient.isConnected();
+ }
+
+ @Override
+ public void disconnect() throws IOException
+ {
+ try
+ {
+ getFtpClient().quit();
+ }
+ catch (IOException e)
+ {
+ LOG.debug("I/O exception while trying to quit, probably it's a timed out connection, ignoring.", e);
+ }
+ finally
+ {
+ try
+ {
+ getFtpClient().disconnect();
+ }
+ catch (IOException e)
+ {
+ LOG.warn("I/O exception while trying to disconnect, probably it's a closed connection, ignoring.", e);
+ }
+ finally
+ {
+ ftpClient = null;
+ }
+ }
+ }
+
+ @Override
+ public FTPFile[] listFiles(final String relPath) throws IOException
+ {
+ try
+ {
+ // VFS-210: return getFtpClient().listFiles(relPath);
+ final FTPFile[] files = listFilesInDirectory(relPath);
+ return files;
+ }
+ catch (final IOException e)
+ {
+ disconnect();
+ final FTPFile[] files = listFilesInDirectory(relPath);
+ return files;
+ }
+ }
+
+ private FTPFile[] listFilesInDirectory(final String relPath) throws IOException
+ {
+ FTPFile[] files;
+
+ // VFS-307: no check if we can simply list the files, this might fail if there are spaces in the path
+ files = getFtpClient().listFiles(relPath);
+ if (FTPReply.isPositiveCompletion(getFtpClient().getReplyCode()))
+ {
+ return files;
+ }
+
+ // VFS-307: now try the hard way by cd'ing into the directory, list and cd back
+ // if VFS is required to fallback here the user might experience a real bad FTP performance
+ // as then every list requires 4 ftp commands.
+ String workingDirectory = null;
+ if (relPath != null)
+ {
+ workingDirectory = getFtpClient().printWorkingDirectory();
+ if (!getFtpClient().changeWorkingDirectory(relPath))
+ {
+ return null;
+ }
+ }
+
+ files = getFtpClient().listFiles();
+
+ if (relPath != null && !getFtpClient().changeWorkingDirectory(workingDirectory))
+ {
+ throw new FileSystemException("vfs.provider.ftp.wrapper/change-work-directory-back.error",
+ workingDirectory);
+ }
+ return files;
+ }
+
+ @Override
+ public boolean removeDirectory(final String relPath) throws IOException
+ {
+ try
+ {
+ return getFtpClient().removeDirectory(relPath);
+ }
+ catch (final IOException e)
+ {
+ disconnect();
+ return getFtpClient().removeDirectory(relPath);
+ }
+ }
+
+ @Override
+ public boolean deleteFile(final String relPath) throws IOException
+ {
+ try
+ {
+ return getFtpClient().deleteFile(relPath);
+ }
+ catch (final IOException e)
+ {
+ disconnect();
+ return getFtpClient().deleteFile(relPath);
+ }
+ }
+
+ @Override
+ public boolean rename(final String oldName, final String newName) throws IOException
+ {
+ try
+ {
+ return getFtpClient().rename(oldName, newName);
+ }
+ catch (final IOException e)
+ {
+ disconnect();
+ return getFtpClient().rename(oldName, newName);
+ }
+ }
+
+ @Override
+ public boolean makeDirectory(final String relPath) throws IOException
+ {
+ try
+ {
+ return getFtpClient().makeDirectory(relPath);
+ }
+ catch (final IOException e)
+ {
+ disconnect();
+ return getFtpClient().makeDirectory(relPath);
+ }
+ }
+
+ @Override
+ public boolean completePendingCommand() throws IOException
+ {
+ if (ftpClient != null)
+ {
+ return getFtpClient().completePendingCommand();
+ }
+
+ return true;
+ }
+
+ @Override
+ public InputStream retrieveFileStream(final String relPath) throws IOException
+ {
+ try
+ {
+ return getFtpClient().retrieveFileStream(relPath);
+ }
+ catch (final IOException e)
+ {
+ disconnect();
+ return getFtpClient().retrieveFileStream(relPath);
+ }
+ }
+
+ @Override
+ public InputStream retrieveFileStream(final String relPath, final long restartOffset) throws IOException
+ {
+ try
+ {
+ final FTPClient client = getFtpClient();
+ client.setRestartOffset(restartOffset);
+ return client.retrieveFileStream(relPath);
+ }
+ catch (final IOException e)
+ {
+ disconnect();
+ final FTPClient client = getFtpClient();
+ client.setRestartOffset(restartOffset);
+ return client.retrieveFileStream(relPath);
+ }
+ }
+
+ @Override
+ public OutputStream appendFileStream(final String relPath) throws IOException
+ {
+ try
+ {
+ return getFtpClient().appendFileStream(relPath);
+ }
+ catch (final IOException e)
+ {
+ disconnect();
+ return getFtpClient().appendFileStream(relPath);
+ }
+ }
+
+ @Override
+ public OutputStream storeFileStream(final String relPath) throws IOException
+ {
+ try
+ {
+ return getFtpClient().storeFileStream(relPath);
+ }
+ catch (final IOException e)
+ {
+ disconnect();
+ return getFtpClient().storeFileStream(relPath);
+ }
+ }
+
+ @Override
+ public boolean abort() throws IOException
+ {
+ try
+ {
+ // imario@apache.org: 2005-02-14
+ // it should be better to really "abort" the transfer, but
+ // currently I didnt manage to make it work - so lets "abort" the hard way.
+ // return getFtpClient().abort();
+
+ disconnect();
+ return true;
+ }
+ catch (final IOException e)
+ {
+ disconnect();
+ }
+ return true;
+ }
+
+ @Override
+ public String getReplyString() throws IOException
+ {
+ return getFtpClient().getReplyString();
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpClient.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpClient.java
new file mode 100644
index 0000000..df334db
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpClient.java
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ftp;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import org.apache.commons.net.ftp.FTPFile;
+import org.apache.commons.vfs2.FileSystemException;
+
+/**
+ * What VFS expects from an ftp client to provide.
+ */
+public interface FtpClient
+{
+ boolean isConnected() throws FileSystemException;
+
+ void disconnect() throws IOException;
+
+ FTPFile[] listFiles(String relPath) throws IOException;
+
+ boolean removeDirectory(String relPath) throws IOException;
+
+ boolean deleteFile(String relPath) throws IOException;
+
+ boolean rename(String oldName, String newName) throws IOException;
+
+ boolean makeDirectory(String relPath) throws IOException;
+
+ boolean completePendingCommand() throws IOException;
+
+ InputStream retrieveFileStream(String relPath) throws IOException;
+
+ InputStream retrieveFileStream(String relPath, long restartOffset) throws IOException;
+
+ OutputStream appendFileStream(String relPath) throws IOException;
+
+ OutputStream storeFileStream(String relPath) throws IOException;
+
+ boolean abort() throws IOException;
+
+ String getReplyString() throws IOException;
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpClientFactory.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpClientFactory.java
new file mode 100644
index 0000000..d221fa5
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpClientFactory.java
@@ -0,0 +1,305 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ftp;
+
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.io.Writer;
+import java.net.Proxy;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.net.PrintCommandListener;
+import org.apache.commons.net.ftp.FTPClient;
+import org.apache.commons.net.ftp.FTPClientConfig;
+import org.apache.commons.net.ftp.FTPReply;
+import org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
+
+/**
+ * Create a FtpClient instance.
+ */
+public final class FtpClientFactory
+{
+ private FtpClientFactory()
+ {
+ }
+
+ /**
+ * Creates a new connection to the server.
+ *
+ * @param hostname The host name of the server.
+ * @param port The port to connect to.
+ * @param username The name of the user for authentication.
+ * @param password The user's password.
+ * @param workingDirectory The base directory.
+ * @param fileSystemOptions The FileSystemOptions.
+ * @return An FTPClient.
+ * @throws FileSystemException if an error occurs while connecting.
+ */
+ public static FTPClient createConnection(final String hostname, final int port,
+ final char[] username, final char[] password,
+ final String workingDirectory, final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ final FtpConnectionFactory factory = new FtpConnectionFactory(FtpFileSystemConfigBuilder.getInstance());
+ return factory.createConnection(hostname, port, username, password, workingDirectory, fileSystemOptions);
+ }
+
+ /** Connection Factory, used to configure the FTPClient. */
+ public static final class FtpConnectionFactory extends ConnectionFactory<FTPClient, FtpFileSystemConfigBuilder>
+ {
+ private FtpConnectionFactory(final FtpFileSystemConfigBuilder builder)
+ {
+ super(builder);
+ }
+
+ @Override
+ protected FTPClient createClient(final FileSystemOptions fileSystemOptions)
+ {
+ return new FTPClient();
+ }
+
+ @Override
+ protected void setupOpenConnection(final FTPClient client, final FileSystemOptions fileSystemOptions)
+ {
+ // nothing to do for FTP
+ }
+ }
+
+ /** Abstract Factory, used to configure different FTPClients. */
+ public abstract static class ConnectionFactory<C extends FTPClient, B extends FtpFileSystemConfigBuilder>
+ {
+ private static final char[] ANON_CHAR_ARRAY = "anonymous".toCharArray();
+ private static final int BUFSZ = 40;
+ private final Log log = LogFactory.getLog(getClass());
+
+ protected B builder;
+
+ protected ConnectionFactory(final B builder)
+ {
+ this.builder = builder;
+ }
+
+ public C createConnection(final String hostname, final int port, char[] username, char[] password,
+ final String workingDirectory, final FileSystemOptions fileSystemOptions) throws FileSystemException
+ {
+ // Determine the username and password to use
+ if (username == null)
+ {
+ username = ANON_CHAR_ARRAY;
+ }
+
+ if (password == null)
+ {
+ password = ANON_CHAR_ARRAY;
+ }
+
+ try
+ {
+ final C client = createClient(fileSystemOptions);
+
+ if (log.isDebugEnabled())
+ {
+ final Writer writer = new StringWriter(1024)
+ {
+ @Override
+ public void flush()
+ {
+ final StringBuffer buffer = getBuffer();
+ String message = buffer.toString();
+ if (message.toUpperCase().startsWith("PASS ") && message.length() > 5)
+ {
+ message = "PASS ***";
+ }
+ log.debug(message);
+ buffer.setLength(0);
+ }
+ };
+ client.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(writer)));
+ }
+
+ configureClient(fileSystemOptions, client);
+
+ final FTPFileEntryParserFactory myFactory =
+ builder.getEntryParserFactory(fileSystemOptions);
+ if (myFactory != null)
+ {
+ client.setParserFactory(myFactory);
+ }
+
+ Boolean remoteVerification = builder.getRemoteVerification(fileSystemOptions);
+ if (remoteVerification != null)
+ {
+ client.setRemoteVerificationEnabled(remoteVerification.booleanValue());
+ }
+
+ try
+ {
+ // Set connect timeout
+ final Integer connectTimeout = builder.getConnectTimeout(fileSystemOptions);
+ if (connectTimeout != null)
+ {
+ client.setDefaultTimeout(connectTimeout.intValue());
+ }
+
+ final String controlEncoding = builder.getControlEncoding(fileSystemOptions);
+ if (controlEncoding != null)
+ {
+ client.setControlEncoding(controlEncoding);
+ }
+
+ final Proxy proxy = builder.getProxy(fileSystemOptions);
+ if (proxy != null)
+ {
+ client.setProxy(proxy);
+ }
+
+ client.connect(hostname, port);
+
+ final int reply = client.getReplyCode();
+ if (!FTPReply.isPositiveCompletion(reply))
+ {
+ throw new FileSystemException("vfs.provider.ftp/connect-rejected.error", hostname);
+ }
+
+ // Login
+ if (!client.login(
+ UserAuthenticatorUtils.toString(username),
+ UserAuthenticatorUtils.toString(password)))
+ {
+ throw new FileSystemException("vfs.provider.ftp/login.error",
+ hostname, UserAuthenticatorUtils.toString(username));
+ }
+
+ FtpFileType fileType = builder.getFileType(fileSystemOptions);
+ if (fileType == null)
+ {
+ fileType = FtpFileType.BINARY;
+ }
+ // Set binary mode
+ if (!client.setFileType(fileType.getValue()))
+ {
+ throw new FileSystemException("vfs.provider.ftp/set-file-type.error", fileType);
+ }
+
+ // Set dataTimeout value
+ final Integer dataTimeout = builder.getDataTimeout(fileSystemOptions);
+ if (dataTimeout != null)
+ {
+ client.setDataTimeout(dataTimeout.intValue());
+ }
+
+ final Integer socketTimeout = builder.getSoTimeout(fileSystemOptions);
+ if (socketTimeout != null)
+ {
+ client.setSoTimeout(socketTimeout.intValue());
+ }
+
+ final Boolean userDirIsRoot = builder.getUserDirIsRoot(fileSystemOptions);
+ if (workingDirectory != null && (userDirIsRoot == null || !userDirIsRoot.booleanValue()))
+ {
+ if (!client.changeWorkingDirectory(workingDirectory))
+ {
+ throw new FileSystemException("vfs.provider.ftp/change-work-directory.error",
+ workingDirectory);
+ }
+ }
+
+ final Boolean passiveMode = builder.getPassiveMode(fileSystemOptions);
+ if (passiveMode != null && passiveMode.booleanValue())
+ {
+ client.enterLocalPassiveMode();
+ }
+
+ setupOpenConnection(client, fileSystemOptions);
+ }
+ catch (final IOException e)
+ {
+ if (client.isConnected())
+ {
+ client.disconnect();
+ }
+ throw e;
+ }
+
+ return client;
+ }
+ catch (final Exception exc)
+ {
+ throw new FileSystemException("vfs.provider.ftp/connect.error", exc, hostname);
+ }
+ }
+
+ protected abstract C createClient(FileSystemOptions fileSystemOptions) throws FileSystemException;
+ protected abstract void setupOpenConnection(C client, FileSystemOptions fileSystemOptions) throws IOException;
+
+ private void configureClient(final FileSystemOptions fileSystemOptions, final C client)
+ {
+ final String key = builder.getEntryParser(fileSystemOptions);
+ if (key != null)
+ {
+ final FTPClientConfig config = new FTPClientConfig(key);
+
+ final String serverLanguageCode =
+ builder.getServerLanguageCode(fileSystemOptions);
+ if (serverLanguageCode != null)
+ {
+ config.setServerLanguageCode(serverLanguageCode);
+ }
+ final String defaultDateFormat =
+ builder.getDefaultDateFormat(fileSystemOptions);
+ if (defaultDateFormat != null)
+ {
+ config.setDefaultDateFormatStr(defaultDateFormat);
+ }
+ final String recentDateFormat =
+ builder.getRecentDateFormat(fileSystemOptions);
+ if (recentDateFormat != null)
+ {
+ config.setRecentDateFormatStr(recentDateFormat);
+ }
+ final String serverTimeZoneId =
+ builder.getServerTimeZoneId(fileSystemOptions);
+ if (serverTimeZoneId != null)
+ {
+ config.setServerTimeZoneId(serverTimeZoneId);
+ }
+ final String[] shortMonthNames =
+ builder.getShortMonthNames(fileSystemOptions);
+ if (shortMonthNames != null)
+ {
+ final StringBuilder shortMonthNamesStr = new StringBuilder(BUFSZ);
+ for (final String shortMonthName : shortMonthNames)
+ {
+ if (shortMonthNamesStr.length() > 0)
+ {
+ shortMonthNamesStr.append("|");
+ }
+ shortMonthNamesStr.append(shortMonthName);
+ }
+ config.setShortMonthNames(shortMonthNamesStr.toString());
+ }
+
+ client.configure(config);
+ }
+ }
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileNameParser.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileNameParser.java
new file mode 100644
index 0000000..73675a9
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileNameParser.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ftp;
+
+import org.apache.commons.vfs2.provider.FileNameParser;
+import org.apache.commons.vfs2.provider.HostFileNameParser;
+
+/**
+ * Implementation for ftp. set default port to 21
+ */
+public class FtpFileNameParser extends HostFileNameParser
+{
+ private static final FtpFileNameParser INSTANCE = new FtpFileNameParser();
+
+ private static final int PORT = 21;
+
+ public FtpFileNameParser()
+ {
+ super(PORT);
+ }
+
+ public static FileNameParser getInstance()
+ {
+ return INSTANCE;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileObject.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileObject.java
new file mode 100644
index 0000000..2dedf3f
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileObject.java
@@ -0,0 +1,792 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ftp;
+
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.Calendar;
+import java.util.Collections;
+import java.util.Iterator;
+import java.util.Map;
+import java.util.TreeMap;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.net.ftp.FTPFile;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileNotFolderException;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.RandomAccessContent;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileObject;
+import org.apache.commons.vfs2.provider.UriParser;
+import org.apache.commons.vfs2.util.FileObjectUtils;
+import org.apache.commons.vfs2.util.Messages;
+import org.apache.commons.vfs2.util.MonitorInputStream;
+import org.apache.commons.vfs2.util.MonitorOutputStream;
+import org.apache.commons.vfs2.util.RandomAccessMode;
+
+/**
+ * An FTP file.
+ */
+public class FtpFileObject extends AbstractFileObject<FtpFileSystem>
+{
+ private static final Map<String, FTPFile> EMPTY_FTP_FILE_MAP =
+ Collections.unmodifiableMap(new TreeMap<String, FTPFile>());
+ private static final FTPFile UNKNOWN = new FTPFile();
+ private static final Log log = LogFactory.getLog(FtpFileObject.class);
+
+ private final String relPath;
+
+ // Cached info
+ private FTPFile fileInfo;
+ private Map<String, FTPFile> children;
+ private FileObject linkDestination;
+
+ private boolean inRefresh;
+
+ protected FtpFileObject(final AbstractFileName name,
+ final FtpFileSystem fileSystem,
+ final FileName rootName)
+ throws FileSystemException
+ {
+ super(name, fileSystem);
+ final String relPath = UriParser.decode(rootName.getRelativeName(name));
+ if (".".equals(relPath))
+ {
+ // do not use the "." as path against the ftp-server
+ // e.g. the uu.net ftp-server do a recursive listing then
+ // this.relPath = UriParser.decode(rootName.getPath());
+ // this.relPath = ".";
+ this.relPath = null;
+ }
+ else
+ {
+ this.relPath = relPath;
+ }
+ }
+
+ /**
+ * Called by child file objects, to locate their ftp file info.
+ *
+ * @param name the filename in its native form ie. without uri stuff (%nn)
+ * @param flush recreate children cache
+ */
+ private FTPFile getChildFile(final String name, final boolean flush) throws IOException
+ {
+ /* If we should flush cached children, clear our children map unless
+ * we're in the middle of a refresh in which case we've just recently
+ * refreshed our children. No need to do it again when our children are
+ * refresh()ed, calling getChildFile() for themselves from within
+ * getInfo(). See getChildren(). */
+ if (flush && !inRefresh)
+ {
+ children = null;
+ }
+
+ // List the children of this file
+ doGetChildren();
+
+ // VFS-210
+ if (children == null)
+ {
+ return null;
+ }
+
+ // Look for the requested child
+ final FTPFile ftpFile = children.get(name);
+ return ftpFile;
+ }
+
+ /**
+ * Fetches the children of this file, if not already cached.
+ */
+ private void doGetChildren() throws IOException
+ {
+ if (children != null)
+ {
+ return;
+ }
+
+ final FtpClient client = getAbstractFileSystem().getClient();
+ try
+ {
+ final String path = fileInfo != null && fileInfo.isSymbolicLink()
+ ? getFileSystem().getFileSystemManager().
+ resolveName(getParent().getName(), fileInfo.getLink()).getPath()
+ : relPath;
+ final FTPFile[] tmpChildren = client.listFiles(path);
+ if (tmpChildren == null || tmpChildren.length == 0)
+ {
+ children = EMPTY_FTP_FILE_MAP;
+ }
+ else
+ {
+ children = new TreeMap<String, FTPFile>();
+
+ // Remove '.' and '..' elements
+ for (int i = 0; i < tmpChildren.length; i++)
+ {
+ final FTPFile child = tmpChildren[i];
+ if (child == null)
+ {
+ if (log.isDebugEnabled())
+ {
+ log.debug(Messages.getString("vfs.provider.ftp/invalid-directory-entry.debug",
+ Integer.valueOf(i), relPath));
+ }
+ continue;
+ }
+ if (!".".equals(child.getName())
+ && !"..".equals(child.getName()))
+ {
+ children.put(child.getName(), child);
+ }
+ }
+ }
+ }
+ finally
+ {
+ getAbstractFileSystem().putClient(client);
+ }
+ }
+
+ /**
+ * Attaches this file object to its file resource.
+ */
+ @Override
+ protected void doAttach()
+ throws IOException
+ {
+ // Get the parent folder to find the info for this file
+ // VFS-210 getInfo(false);
+ }
+
+ /**
+ * Fetches the info for this file.
+ */
+ private void getInfo(final boolean flush) throws IOException
+ {
+ final FtpFileObject parent = (FtpFileObject) FileObjectUtils.getAbstractFileObject(getParent());
+ FTPFile newFileInfo;
+ if (parent != null)
+ {
+ newFileInfo = parent.getChildFile(UriParser.decode(getName().getBaseName()), flush);
+ }
+ else
+ {
+ // Assume the root is a directory and exists
+ newFileInfo = new FTPFile();
+ newFileInfo.setType(FTPFile.DIRECTORY_TYPE);
+ }
+
+ if (newFileInfo == null)
+ {
+ this.fileInfo = UNKNOWN;
+ }
+ else
+ {
+ this.fileInfo = newFileInfo;
+ }
+ }
+
+ /**
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public void refresh() throws FileSystemException
+ {
+ if (!inRefresh)
+ {
+ try
+ {
+ inRefresh = true;
+ super.refresh();
+
+ synchronized (getFileSystem())
+ {
+ this.fileInfo = null;
+ }
+
+ /* VFS-210
+ try
+ {
+ // this will tell the parent to recreate its children collection
+ getInfo(true);
+ }
+ catch (IOException e)
+ {
+ throw new FileSystemException(e);
+ }
+ */
+ }
+ finally
+ {
+ inRefresh = false;
+ }
+ }
+ }
+
+ /**
+ * Detaches this file object from its file resource.
+ */
+ @Override
+ protected void doDetach()
+ {
+ synchronized (getFileSystem())
+ {
+ this.fileInfo = null;
+ children = null;
+ }
+ }
+
+ /**
+ * Called when the children of this file change.
+ */
+ @Override
+ protected void onChildrenChanged(final FileName child, final FileType newType)
+ {
+ if (children != null && newType.equals(FileType.IMAGINARY))
+ {
+ try
+ {
+ children.remove(UriParser.decode(child.getBaseName()));
+ }
+ catch (final FileSystemException e)
+ {
+ throw new RuntimeException(e.getMessage());
+ }
+ }
+ else
+ {
+ // if child was added we have to rescan the children
+ // TODO - get rid of this
+ children = null;
+ }
+ }
+
+ /**
+ * Called when the type or content of this file changes.
+ */
+ @Override
+ protected void onChange() throws IOException
+ {
+ children = null;
+
+ if (getType().equals(FileType.IMAGINARY))
+ {
+ // file is deleted, avoid server lookup
+ synchronized (getFileSystem())
+ {
+ this.fileInfo = UNKNOWN;
+ }
+ return;
+ }
+
+ getInfo(true);
+ }
+
+ /**
+ * Determines the type of the file, returns null if the file does not
+ * exist.
+ */
+ @Override
+ protected FileType doGetType()
+ throws Exception
+ {
+ // VFS-210
+ synchronized (getFileSystem())
+ {
+ if (this.fileInfo == null)
+ {
+ getInfo(false);
+ }
+
+ if (this.fileInfo == UNKNOWN)
+ {
+ return FileType.IMAGINARY;
+ }
+ else if (this.fileInfo.isDirectory())
+ {
+ return FileType.FOLDER;
+ }
+ else if (this.fileInfo.isFile())
+ {
+ return FileType.FILE;
+ }
+ else if (this.fileInfo.isSymbolicLink())
+ {
+ final FileObject linkDest = getLinkDestination();
+ // VFS-437: We need to check if the symbolic link links back to the symbolic link itself
+ if (this.isCircular(linkDest))
+ {
+ // If the symbolic link links back to itself, treat it as an imaginary file to prevent following
+ // this link. If the user tries to access the link as a file or directory, the user will end up with
+ // a FileSystemException warning that the file cannot be accessed. This is to prevent the infinite
+ // call back to doGetType() to prevent the StackOverFlow
+ return FileType.IMAGINARY;
+ }
+ return linkDest.getType();
+
+ }
+ }
+ throw new FileSystemException("vfs.provider.ftp/get-type.error", getName());
+ }
+
+ private FileObject getLinkDestination() throws FileSystemException
+ {
+ if (linkDestination == null)
+ {
+ final String path;
+ synchronized (getFileSystem())
+ {
+ path = this.fileInfo.getLink();
+ }
+ FileName relativeTo = getName().getParent();
+ if (relativeTo == null)
+ {
+ relativeTo = getName();
+ }
+ final FileName linkDestinationName = getFileSystem().getFileSystemManager().resolveName(relativeTo, path);
+ linkDestination = getFileSystem().resolveFile(linkDestinationName);
+ }
+
+ return linkDestination;
+ }
+
+ @Override
+ protected FileObject[] doListChildrenResolved() throws Exception
+ {
+ synchronized (getFileSystem())
+ {
+ if (this.fileInfo != null && this.fileInfo.isSymbolicLink())
+ {
+ final FileObject linkDest = getLinkDestination();
+ // VFS-437: Try to avoid a recursion loop.
+ if (this.isCircular(linkDest))
+ {
+ return null;
+ }
+ return linkDest.getChildren();
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns the file's list of children.
+ *
+ * @return The list of children
+ * @throws FileSystemException If there was a problem listing children
+ * @see AbstractFileObject#getChildren()
+ * @since 2.0
+ */
+ @Override
+ public FileObject[] getChildren() throws FileSystemException
+ {
+ try
+ {
+ if (doGetType() != FileType.FOLDER)
+ {
+ throw new FileNotFolderException(getName());
+ }
+ }
+ catch (final Exception ex)
+ {
+ throw new FileNotFolderException(getName(), ex);
+ }
+
+ try
+ {
+ /* Wrap our parent implementation, noting that we're refreshing so
+ * that we don't refresh() ourselves and each of our parents for
+ * each children. Note that refresh() will list children. Meaning,
+ * if if this file has C children, P parents, there will be (C * P)
+ * listings made with (C * (P + 1)) refreshes, when there should
+ * really only be 1 listing and C refreshes. */
+
+ this.inRefresh = true;
+ return super.getChildren();
+ }
+ finally
+ {
+ this.inRefresh = false;
+ }
+ }
+
+ /**
+ * Lists the children of the file.
+ */
+ @Override
+ protected String[] doListChildren()
+ throws Exception
+ {
+ // List the children of this file
+ doGetChildren();
+
+ // VFS-210
+ if (children == null)
+ {
+ return null;
+ }
+
+ // TODO - get rid of this children stuff
+ final String[] childNames = new String[children.size()];
+ int childNum = -1;
+ final Iterator<FTPFile> iterChildren = children.values().iterator();
+ while (iterChildren.hasNext())
+ {
+ childNum++;
+ final FTPFile child = iterChildren.next();
+ childNames[childNum] = child.getName();
+ }
+
+ return UriParser.encode(childNames);
+ }
+
+ /**
+ * Deletes the file.
+ */
+ @Override
+ protected void doDelete() throws Exception
+ {
+ synchronized (getFileSystem())
+ {
+ final boolean ok;
+ final FtpClient ftpClient = getAbstractFileSystem().getClient();
+ try
+ {
+ if (this.fileInfo.isDirectory())
+ {
+ ok = ftpClient.removeDirectory(relPath);
+ }
+ else
+ {
+ ok = ftpClient.deleteFile(relPath);
+ }
+ }
+ finally
+ {
+ getAbstractFileSystem().putClient(ftpClient);
+ }
+
+ if (!ok)
+ {
+ throw new FileSystemException("vfs.provider.ftp/delete-file.error", getName());
+ }
+ this.fileInfo = null;
+ children = EMPTY_FTP_FILE_MAP;
+ }
+ }
+
+ /**
+ * Renames the file
+ */
+ @Override
+ protected void doRename(final FileObject newFile) throws Exception
+ {
+ synchronized (getFileSystem())
+ {
+ final boolean ok;
+ final FtpClient ftpClient = getAbstractFileSystem().getClient();
+ try
+ {
+ final String oldName = getName().getPath();
+ final String newName = newFile.getName().getPath();
+ ok = ftpClient.rename(oldName, newName);
+ }
+ finally
+ {
+ getAbstractFileSystem().putClient(ftpClient);
+ }
+
+ if (!ok)
+ {
+ throw new FileSystemException("vfs.provider.ftp/rename-file.error",
+ getName().toString(), newFile);
+ }
+ this.fileInfo = null;
+ children = EMPTY_FTP_FILE_MAP;
+ }
+ }
+
+ /**
+ * Creates this file as a folder.
+ */
+ @Override
+ protected void doCreateFolder()
+ throws Exception
+ {
+ final boolean ok;
+ final FtpClient client = getAbstractFileSystem().getClient();
+ try
+ {
+ ok = client.makeDirectory(relPath);
+ }
+ finally
+ {
+ getAbstractFileSystem().putClient(client);
+ }
+
+ if (!ok)
+ {
+ throw new FileSystemException("vfs.provider.ftp/create-folder.error", getName());
+ }
+ }
+
+ /**
+ * Returns the size of the file content (in bytes).
+ */
+ @Override
+ protected long doGetContentSize() throws Exception
+ {
+ synchronized (getFileSystem())
+ {
+ if (this.fileInfo.isSymbolicLink())
+ {
+ final FileObject linkDest = getLinkDestination();
+ // VFS-437: Try to avoid a recursion loop.
+ if (this.isCircular(linkDest))
+ {
+ return this.fileInfo.getSize();
+ }
+ return linkDest.getContent().getSize();
+ }
+ else
+ {
+ return this.fileInfo.getSize();
+ }
+ }
+ }
+
+ /**
+ * get the last modified time on an ftp file
+ *
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doGetLastModifiedTime()
+ */
+ @Override
+ protected long doGetLastModifiedTime() throws Exception
+ {
+ synchronized (getFileSystem())
+ {
+ if (this.fileInfo.isSymbolicLink())
+ {
+ final FileObject linkDest = getLinkDestination();
+ // VFS-437: Try to avoid a recursion loop.
+ if (this.isCircular(linkDest))
+ {
+ return getTimestamp();
+ }
+ return linkDest.getContent().getLastModifiedTime();
+ }
+ else
+ {
+ return getTimestamp();
+ }
+ }
+ }
+
+ /**
+ * Creates an input stream to read the file content from.
+ */
+ @Override
+ protected InputStream doGetInputStream() throws Exception
+ {
+ final FtpClient client = getAbstractFileSystem().getClient();
+ try
+ {
+ final InputStream instr = client.retrieveFileStream(relPath);
+ // VFS-210
+ if (instr == null)
+ {
+ throw new FileNotFoundException(getName().toString());
+ }
+ return new FtpInputStream(client, instr);
+ }
+ catch (final Exception e)
+ {
+ getAbstractFileSystem().putClient(client);
+ throw e;
+ }
+ }
+
+ @Override
+ protected RandomAccessContent doGetRandomAccessContent(final RandomAccessMode mode) throws Exception
+ {
+ return new FtpRandomAccessContent(this, mode);
+ }
+
+ /**
+ * Creates an output stream to write the file content to.
+ */
+ @Override
+ protected OutputStream doGetOutputStream(final boolean bAppend)
+ throws Exception
+ {
+ final FtpClient client = getAbstractFileSystem().getClient();
+ try
+ {
+ OutputStream out = null;
+ if (bAppend)
+ {
+ out = client.appendFileStream(relPath);
+ }
+ else
+ {
+ out = client.storeFileStream(relPath);
+ }
+
+ if (out == null)
+ {
+ throw new FileSystemException("vfs.provider.ftp/output-error.debug",
+ this.getName(),
+ client.getReplyString());
+ }
+
+ return new FtpOutputStream(client, out);
+ }
+ catch (final Exception e)
+ {
+ getAbstractFileSystem().putClient(client);
+ throw e;
+ }
+ }
+
+ String getRelPath()
+ {
+ return relPath;
+ }
+
+ private long getTimestamp()
+ {
+ final Calendar timestamp = this.fileInfo.getTimestamp();
+ return timestamp == null ? 0L : timestamp.getTime().getTime();
+ }
+
+ /**
+ * This is an over simplistic implementation for VFS-437.
+ */
+ private boolean isCircular(final FileObject linkDest) throws FileSystemException
+ {
+ return linkDest.getName().getPathDecoded().equals(this.getName().getPathDecoded());
+ }
+
+ FtpInputStream getInputStream(final long filePointer) throws IOException
+ {
+ final FtpClient client = getAbstractFileSystem().getClient();
+ try
+ {
+ final InputStream instr = client.retrieveFileStream(relPath, filePointer);
+ if (instr == null)
+ {
+ throw new FileSystemException("vfs.provider.ftp/input-error.debug",
+ this.getName(),
+ client.getReplyString());
+ }
+ return new FtpInputStream(client, instr);
+ }
+ catch (final IOException e)
+ {
+ getAbstractFileSystem().putClient(client);
+ throw e;
+ }
+ }
+
+ /**
+ * An InputStream that monitors for end-of-file.
+ */
+ class FtpInputStream
+ extends MonitorInputStream
+ {
+ private final FtpClient client;
+
+ public FtpInputStream(final FtpClient client, final InputStream in)
+ {
+ super(in);
+ this.client = client;
+ }
+
+ void abort() throws IOException
+ {
+ client.abort();
+ close();
+ }
+
+ /**
+ * Called after the stream has been closed.
+ */
+ @Override
+ protected void onClose() throws IOException
+ {
+ final boolean ok;
+ try
+ {
+ ok = client.completePendingCommand();
+ }
+ finally
+ {
+ getAbstractFileSystem().putClient(client);
+ }
+
+ if (!ok)
+ {
+ throw new FileSystemException("vfs.provider.ftp/finish-get.error", getName());
+ }
+ }
+ }
+
+ /**
+ * An OutputStream that monitors for end-of-file.
+ */
+ private class FtpOutputStream
+ extends MonitorOutputStream
+ {
+ private final FtpClient client;
+
+ public FtpOutputStream(final FtpClient client, final OutputStream outstr)
+ {
+ super(outstr);
+ this.client = client;
+ }
+
+ /**
+ * Called after this stream is closed.
+ */
+ @Override
+ protected void onClose() throws IOException
+ {
+ final boolean ok;
+ try
+ {
+ ok = client.completePendingCommand();
+ }
+ finally
+ {
+ getAbstractFileSystem().putClient(client);
+ }
+
+ if (!ok)
+ {
+ throw new FileSystemException("vfs.provider.ftp/finish-put.error", getName());
+ }
+ }
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileProvider.java
new file mode 100644
index 0000000..043e7ba
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileProvider.java
@@ -0,0 +1,110 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ftp;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemConfigBuilder;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.UserAuthenticationData;
+import org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider;
+import org.apache.commons.vfs2.provider.GenericFileName;
+
+/**
+ * A provider for FTP file systems.
+ */
+public class FtpFileProvider
+ extends AbstractOriginatingFileProvider
+{
+ /**
+ * File Entry Parser.
+ */
+ public static final String ATTR_FILE_ENTRY_PARSER = "FEP";
+
+ /**
+ * Authenticator types.
+ */
+ public static final UserAuthenticationData.Type[] AUTHENTICATOR_TYPES = new UserAuthenticationData.Type[]
+ {
+ UserAuthenticationData.USERNAME, UserAuthenticationData.PASSWORD
+ };
+
+ static final Collection<Capability> capabilities = Collections.unmodifiableCollection(Arrays.asList(new Capability[]
+ {
+ Capability.CREATE,
+ Capability.DELETE,
+ Capability.RENAME,
+ Capability.GET_TYPE,
+ Capability.LIST_CHILDREN,
+ Capability.READ_CONTENT,
+ Capability.GET_LAST_MODIFIED,
+ Capability.URI,
+ Capability.WRITE_CONTENT,
+ Capability.APPEND_CONTENT,
+ Capability.RANDOM_ACCESS_READ,
+ }));
+
+ /**
+ * Constructs a new provider.
+ */
+ public FtpFileProvider()
+ {
+ super();
+ setFileNameParser(FtpFileNameParser.getInstance());
+ }
+
+ /**
+ * Creates the filesystem.
+ */
+ @Override
+ protected FileSystem doCreateFileSystem(final FileName name, final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ // Create the file system
+ final GenericFileName rootName = (GenericFileName) name;
+
+ final FTPClientWrapper ftpClient = new FTPClientWrapper(rootName, fileSystemOptions);
+ /*
+ FTPClient ftpClient = FtpClientFactory.createConnection(rootName.getHostName(),
+ rootName.getPort(),
+ rootName.getUserName(),
+ rootName.getPassword(),
+ rootName.getPath(),
+ fileSystemOptions);
+ */
+
+ return new FtpFileSystem(rootName, ftpClient, fileSystemOptions);
+ }
+
+ @Override
+ public FileSystemConfigBuilder getConfigBuilder()
+ {
+ return FtpFileSystemConfigBuilder.getInstance();
+ }
+
+ @Override
+ public Collection<Capability> getCapabilities()
+ {
+ return capabilities;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileSystem.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileSystem.java
new file mode 100644
index 0000000..18cdeec
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileSystem.java
@@ -0,0 +1,158 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ftp;
+
+import java.io.IOException;
+import java.util.Collection;
+import java.util.concurrent.atomic.AtomicReference;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.VfsLog;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileSystem;
+import org.apache.commons.vfs2.provider.GenericFileName;
+
+/**
+ * An FTP file system.
+ */
+public class FtpFileSystem extends AbstractFileSystem
+{
+ private static final Log LOG = LogFactory.getLog(FtpFileSystem.class);
+
+// private final String hostname;
+// private final int port;
+// private final String username;
+// private final String password;
+
+ // An idle client
+ private final AtomicReference<FtpClient> idleClient = new AtomicReference<FtpClient>();
+
+ /**
+ * @param rootName The root of the file system.
+ * @param ftpClient The FtpClient.
+ * @param fileSystemOptions The FileSystemOptions.
+ * @since 2.0 (was protected)
+ * */
+ public FtpFileSystem(final GenericFileName rootName, final FtpClient ftpClient,
+ final FileSystemOptions fileSystemOptions)
+ {
+ super(rootName, null, fileSystemOptions);
+ // hostname = rootName.getHostName();
+ // port = rootName.getPort();
+
+ idleClient.set(ftpClient);
+ }
+
+ @Override
+ protected void doCloseCommunicationLink()
+ {
+ final FtpClient idle = idleClient.getAndSet(null);
+ // Clean up the connection
+ if (idle != null)
+ {
+ closeConnection(idle);
+ }
+ }
+
+ /**
+ * Adds the capabilities of this file system.
+ */
+ @Override
+ protected void addCapabilities(final Collection<Capability> caps)
+ {
+ caps.addAll(FtpFileProvider.capabilities);
+ }
+
+ /**
+ * Cleans up the connection to the server.
+ * @param client The FtpClient.
+ */
+ private void closeConnection(final FtpClient client)
+ {
+ try
+ {
+ // Clean up
+ if (client.isConnected())
+ {
+ client.disconnect();
+ }
+ }
+ catch (final IOException e)
+ {
+ // getLogger().warn("vfs.provider.ftp/close-connection.error", e);
+ VfsLog.warn(getLogger(), LOG, "vfs.provider.ftp/close-connection.error", e);
+ }
+ }
+
+ /**
+ * Creates an FTP client to use.
+ * @return An FTPCleint.
+ * @throws FileSystemException if an error occurs.
+ */
+ public FtpClient getClient() throws FileSystemException
+ {
+ FtpClient client = idleClient.getAndSet(null);
+
+ if (client == null || !client.isConnected())
+ {
+ client = createWrapper();
+ }
+
+ return client;
+ }
+
+ /**
+ * Get the wrapper to access this file system.
+ * @return new instance.
+ * @throws FileSystemException if any error occurs.
+ * @since 2.1
+ */
+ protected FTPClientWrapper createWrapper() throws FileSystemException
+ {
+ return new FTPClientWrapper((GenericFileName) getRoot().getName(), getFileSystemOptions());
+ }
+
+ /**
+ * Returns an FTP client after use.
+ * @param client The FTPClient.
+ */
+ public void putClient(final FtpClient client)
+ {
+ // Save client for reuse if none is idle.
+ if (!idleClient.compareAndSet(null, client))
+ {
+ // An idle client is already present so close the connection.
+ closeConnection(client);
+ }
+ }
+
+
+ /**
+ * Creates a file object.
+ */
+ @Override
+ protected FileObject createFile(final AbstractFileName name)
+ throws FileSystemException
+ {
+ return new FtpFileObject(name, this, getRootName());
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileSystemConfigBuilder.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileSystemConfigBuilder.java
new file mode 100644
index 0000000..2066bdc
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileSystemConfigBuilder.java
@@ -0,0 +1,467 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ftp;
+
+import java.net.Proxy;
+
+import org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemConfigBuilder;
+import org.apache.commons.vfs2.FileSystemOptions;
+
+/**
+ * The config builder for various ftp configuration options.
+ */
+public class FtpFileSystemConfigBuilder extends FileSystemConfigBuilder
+{
+ private static final String _PREFIX = FtpFileSystemConfigBuilder.class.getName();
+
+ private static final FtpFileSystemConfigBuilder BUILDER = new FtpFileSystemConfigBuilder();
+
+ private static final String CONNECT_TIMEOUT = _PREFIX + ".CONNECT_TIMEOUT";
+ private static final String DATA_TIMEOUT = _PREFIX + ".DATA_TIMEOUT";
+ private static final String DEFAULT_DATE_FORMAT = _PREFIX + ".DEFAULT_DATE_FORMAT";
+ private static final String ENCODING = _PREFIX + ".ENCODING";
+ private static final String FACTORY_KEY = FTPFileEntryParserFactory.class.getName() + ".KEY";
+ private static final String FILE_TYPE = _PREFIX + ".FILE_TYPE";
+ private static final String PASSIVE_MODE = _PREFIX + ".PASSIVE";
+ private static final String PROXY = _PREFIX + ".PROXY";
+ private static final String RECENT_DATE_FORMAT = _PREFIX + ".RECENT_DATE_FORMAT";
+ private static final String REMOTE_VERIFICATION = _PREFIX + ".REMOTE_VERIFICATION";
+ private static final String SERVER_LANGUAGE_CODE = _PREFIX + ".SERVER_LANGUAGE_CODE";
+ private static final String SERVER_TIME_ZONE_ID = _PREFIX + ".SERVER_TIME_ZONE_ID";
+ private static final String SHORT_MONTH_NAMES = _PREFIX + ".SHORT_MONTH_NAMES";
+ private static final String SO_TIMEOUT = _PREFIX + ".SO_TIMEOUT";
+ private static final String USER_DIR_IS_ROOT = _PREFIX + ".USER_DIR_IS_ROOT";
+
+ private FtpFileSystemConfigBuilder()
+ {
+ super("ftp.");
+ }
+
+ /**
+ * Create new config builder with specified prefix string.
+ * @param prefix prefix string to use for parameters of this config builder.
+ * @since 2.1
+ */
+ protected FtpFileSystemConfigBuilder(final String prefix)
+ {
+ super(prefix);
+ }
+
+ /**
+ * Gets the singleton instance.
+ *
+ * @return the singleton instance.
+ */
+ public static FtpFileSystemConfigBuilder getInstance()
+ {
+ return BUILDER;
+ }
+
+ @Override
+ protected Class<? extends FileSystem> getConfigClass()
+ {
+ return FtpFileSystem.class;
+ }
+
+ /**
+ * Gets the timeout in milliseconds to use for the socket connection.
+ *
+ * @param opts The FileSystemOptions.
+ * @return The timeout in milliseconds to use for the socket connection.
+ * @since 2.1
+ */
+ public Integer getConnectTimeout(final FileSystemOptions opts)
+ {
+ return getInteger(opts, CONNECT_TIMEOUT);
+ }
+
+ /**
+ * @param opts The FileSystemOptions.
+ * @return The encoding.
+ * @since 2.0
+ * */
+ public String getControlEncoding(final FileSystemOptions opts)
+ {
+ return getString(opts, ENCODING);
+ }
+
+ /**
+ * @param opts The FileSystemOptions.
+ * @return The timeout for opening the data channel in milliseconds.
+ * @see #setDataTimeout
+ */
+ public Integer getDataTimeout(final FileSystemOptions opts)
+ {
+ return getInteger(opts, DATA_TIMEOUT);
+ }
+
+ /**
+ * Get the default date format used by the server. See {@link org.apache.commons.net.ftp.FTPClientConfig}
+ * for details and examples.
+ *
+ * @param opts The FileSystemOptions
+ * @return The default date format.
+ */
+ public String getDefaultDateFormat(final FileSystemOptions opts)
+ {
+ return getString(opts, DEFAULT_DATE_FORMAT);
+ }
+
+ /**
+ * @param opts The FileSystemOptions.
+ * @see #setEntryParser
+ * @return the key to the EntryParser.
+ */
+ public String getEntryParser(final FileSystemOptions opts)
+ {
+ return getString(opts, FACTORY_KEY);
+ }
+
+ /**
+ * @param opts The FlleSystemOptions.
+ * @see #setEntryParserFactory
+ * @return An FTPFileEntryParserFactory.
+ */
+ public FTPFileEntryParserFactory getEntryParserFactory(final FileSystemOptions opts)
+ {
+ return (FTPFileEntryParserFactory) getParam(opts, FTPFileEntryParserFactory.class.getName());
+ }
+
+ /**
+ * Gets the file type parameter.
+ *
+ * @param opts The FileSystemOptions.
+ * @return A FtpFileType
+ * @since 2.1
+ */
+ public FtpFileType getFileType(final FileSystemOptions opts)
+ {
+ return getEnum(FtpFileType.class, opts, FILE_TYPE);
+ }
+
+ /**
+ * @param opts The FileSystemOptions.
+ * @return true if passive mode is set.
+ * @see #setPassiveMode
+ */
+ public Boolean getPassiveMode(final FileSystemOptions opts)
+ {
+ return getBoolean(opts, PASSIVE_MODE);
+ }
+
+ /**
+ * Gets the Proxy.
+ *
+ * @param opts The FileSystemOptions.
+ * @return the Proxy
+ * @since 2.1
+ */
+ public Proxy getProxy(final FileSystemOptions opts)
+ {
+ return (Proxy) this.getParam(opts, PROXY);
+ }
+
+ /**
+ * See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
+ *
+ * @param opts The FileSystemOptions.
+ * @return The recent date format.
+ */
+ public String getRecentDateFormat(final FileSystemOptions opts)
+ {
+ return getString(opts, RECENT_DATE_FORMAT);
+ }
+
+ /**
+ * Gets whether to use remote verification.
+ *
+ * @param opts The FileSystemOptions.
+ * @return True if remote verification should be done.
+ */
+ public Boolean getRemoteVerification(FileSystemOptions opts)
+ {
+ return getBoolean(opts, REMOTE_VERIFICATION);
+ }
+
+ /**
+ * Get the language code used by the server. See {@link org.apache.commons.net.ftp.FTPClientConfig}
+ * for details and examples.
+ *
+ * @param opts The FilesystemOptions.
+ * @return The language code of the server.
+ */
+ public String getServerLanguageCode(final FileSystemOptions opts)
+ {
+ return getString(opts, SERVER_LANGUAGE_CODE);
+ }
+
+ /**
+ * See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
+ *
+ * @param opts The FileSystemOptions.
+ * @return The server timezone id.
+ */
+ public String getServerTimeZoneId(final FileSystemOptions opts)
+ {
+ return getString(opts, SERVER_TIME_ZONE_ID);
+ }
+
+ /**
+ * See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
+ *
+ * @param opts The FileSystemOptions.
+ * @return An array of short month names.
+ */
+ public String[] getShortMonthNames(final FileSystemOptions opts)
+ {
+ return (String[]) getParam(opts, SHORT_MONTH_NAMES);
+ }
+
+ /**
+ * @param opts The FileSystem options.
+ * @return The timeout value in milliseconds.
+ * @see #getDataTimeout
+ * @since 2.0
+ */
+ public Integer getSoTimeout(final FileSystemOptions opts)
+ {
+ return getInteger(opts, SO_TIMEOUT);
+ }
+
+ /**
+ * Returns {@link Boolean#TRUE} if VFS should treat the user directory as the root directory. Defaults to
+ * <code>Boolean.TRUE</code> if the method {@link #setUserDirIsRoot(FileSystemOptions, boolean)} has not been
+ * invoked.
+ *
+ * @param opts
+ * The FileSystemOptions.
+ * @return <code>Boolean.TRUE</code> if VFS treats the user directory as the root directory.
+ * @see #setUserDirIsRoot
+ */
+ public Boolean getUserDirIsRoot(final FileSystemOptions opts)
+ {
+ return getBoolean(opts, USER_DIR_IS_ROOT, Boolean.TRUE);
+ }
+
+ /**
+ * Sets the timeout for the initial control connection.
+ * <p>
+ * If you set the connectTimeout to {@code null} no connectTimeout will be set.
+ *
+ * @param opts The FileSystemOptions.
+ * @param connectTimeout the timeout value in milliseconds
+ * @since 2.1
+ */
+ public void setConnectTimeout(final FileSystemOptions opts, final Integer connectTimeout)
+ {
+ setParam(opts, CONNECT_TIMEOUT, connectTimeout);
+ }
+
+ /**
+ * See {@link org.apache.commons.net.ftp.FTP#setControlEncoding} for details and examples.
+ *
+ * @param opts The FileSystemOptions.
+ * @param encoding the encoding to use
+ * @since 2.0
+ */
+ public void setControlEncoding(final FileSystemOptions opts, final String encoding)
+ {
+ setParam(opts, ENCODING, encoding);
+ }
+
+ /**
+ * Set the data timeout for the ftp client.
+ * <p>
+ * If you set the {@code dataTimeout} to {@code null}, no dataTimeout will be set on the
+ * ftp client.
+ *
+ * @param opts The FileSystemOptions.
+ * @param dataTimeout The timeout value.
+ */
+ public void setDataTimeout(final FileSystemOptions opts, final Integer dataTimeout)
+ {
+ setParam(opts, DATA_TIMEOUT, dataTimeout);
+ }
+
+ /**
+ * Set the default date format used by the server. See {@link org.apache.commons.net.ftp.FTPClientConfig}
+ * for details and examples.
+ *
+ * @param opts The FileSystemOptions.
+ * @param defaultDateFormat The default date format.
+ */
+ public void setDefaultDateFormat(final FileSystemOptions opts, final String defaultDateFormat)
+ {
+ setParam(opts, DEFAULT_DATE_FORMAT, defaultDateFormat);
+ }
+
+ /**
+ * Set the FQCN of your FileEntryParser used to parse the directory listing from your server.
+ * <p>
+ * If you do not use the default commons-net FTPFileEntryParserFactory e.g. by using
+ * {@link #setEntryParserFactory} this is the "key" parameter passed as argument into your
+ * custom factory.
+ *
+ * @param opts The FileSystemOptions.
+ * @param key The key.
+ */
+ public void setEntryParser(final FileSystemOptions opts, final String key)
+ {
+ setParam(opts, FACTORY_KEY, key);
+ }
+
+ /**
+ * FTPFileEntryParserFactory which will be used for ftp-entry parsing.
+ *
+ * @param opts The FileSystemOptions.
+ * @param factory instance of your factory
+ */
+ public void setEntryParserFactory(final FileSystemOptions opts, final FTPFileEntryParserFactory factory)
+ {
+ setParam(opts, FTPFileEntryParserFactory.class.getName(), factory);
+ }
+
+ /**
+ * Sets the file type parameter.
+ *
+ * @param opts The FileSystemOptions.
+ * @param ftpFileType A FtpFileType
+ * @since 2.1
+ */
+ public void setFileType(final FileSystemOptions opts, final FtpFileType ftpFileType)
+ {
+ setParam(opts, FILE_TYPE, ftpFileType);
+ }
+
+ /**
+ * Enter into passive mode.
+ *
+ * @param opts The FileSystemOptions.
+ * @param passiveMode true if passive mode should be used.
+ */
+ public void setPassiveMode(final FileSystemOptions opts, final boolean passiveMode)
+ {
+ setParam(opts, PASSIVE_MODE, passiveMode ? Boolean.TRUE : Boolean.FALSE);
+ }
+
+ /**
+ * Sets the Proxy.
+ * <p>
+ * You might need to make sure that {@link #setPassiveMode(FileSystemOptions, boolean) passive mode}
+ * is activated.
+ *
+ * @param opts the FileSystem options.
+ * @param proxy the Proxy
+ * @since 2.1
+ */
+ public void setProxy(final FileSystemOptions opts, Proxy proxy)
+ {
+ setParam(opts, PROXY, proxy);
+ }
+
+ /**
+ * See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
+ *
+ * @param opts The FileSystemOptions.
+ * @param recentDateFormat The recent date format.
+ */
+ public void setRecentDateFormat(final FileSystemOptions opts, final String recentDateFormat)
+ {
+ setParam(opts, RECENT_DATE_FORMAT, recentDateFormat);
+ }
+
+ /**
+ * Sets whether to use remote verification.
+ *
+ * @param opts The FileSystemOptions.
+ * @param remoteVerification True if verification should be done.
+ */
+ public void setRemoteVerification(FileSystemOptions opts, boolean remoteVerification)
+ {
+ setParam(opts, REMOTE_VERIFICATION, remoteVerification);
+ }
+
+ /**
+ * Set the language code used by the server. See {@link org.apache.commons.net.ftp.FTPClientConfig}
+ * for details and examples.
+ *
+ * @param opts The FileSystemOptions.
+ * @param serverLanguageCode The servers language code.
+ */
+ public void setServerLanguageCode(final FileSystemOptions opts, final String serverLanguageCode)
+ {
+ setParam(opts, SERVER_LANGUAGE_CODE, serverLanguageCode);
+ }
+
+ /**
+ * See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
+ *
+ * @param opts The FileSystemOptions.
+ * @param serverTimeZoneId The server timezone id.
+ */
+ public void setServerTimeZoneId(final FileSystemOptions opts, final String serverTimeZoneId)
+ {
+ setParam(opts, SERVER_TIME_ZONE_ID, serverTimeZoneId);
+ }
+
+ /**
+ * See {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
+ *
+ * @param opts The FileSystemOptions.
+ * @param shortMonthNames an array of short month name Strings.
+ */
+ public void setShortMonthNames(final FileSystemOptions opts, final String[] shortMonthNames)
+ {
+ String[] clone = null;
+ if (shortMonthNames != null)
+ {
+ clone = new String[shortMonthNames.length];
+ System.arraycopy(shortMonthNames, 0, clone, 0, shortMonthNames.length);
+ }
+
+ setParam(opts, SHORT_MONTH_NAMES, clone);
+ }
+
+ /**
+ * Sets the socket timeout for the FTP client.
+ * <p>
+ * If you set the {@code soTimeout} to {@code null}, no socket timeout will be set on the
+ * ftp client.
+ *
+ * @param opts The FileSystem options.
+ * @param soTimeout The timeout value in milliseconds.
+ * @since 2.0
+ */
+ public void setSoTimeout(final FileSystemOptions opts, final Integer soTimeout)
+ {
+ setParam(opts, SO_TIMEOUT, soTimeout);
+ }
+
+ /**
+ * Use user directory as root (do not change to fs root).
+ *
+ * @param opts The FileSystemOptions.
+ * @param userDirIsRoot true if the user directory should be treated as the root.
+ */
+ public void setUserDirIsRoot(final FileSystemOptions opts, final boolean userDirIsRoot)
+ {
+ setParam(opts, USER_DIR_IS_ROOT, userDirIsRoot ? Boolean.TRUE : Boolean.FALSE);
+ }
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileType.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileType.java
new file mode 100644
index 0000000..080e3b6
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileType.java
@@ -0,0 +1,73 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ftp;
+
+import org.apache.commons.net.ftp.FTP;
+
+/**
+ * The FTP file types.
+ *
+ * @since 2.1
+ */
+public enum FtpFileType
+{
+ /**
+ * The ASCII file type.
+ */
+ ASCII(FTP.ASCII_FILE_TYPE),
+
+ /**
+ * The binary file type.
+ */
+ BINARY(FTP.BINARY_FILE_TYPE),
+
+ /**
+ * The local file type.
+ */
+ LOCAL(FTP.LOCAL_FILE_TYPE),
+
+ /**
+ * The EBCDIC file type.
+ */
+ EBCDIC(FTP.EBCDIC_FILE_TYPE);
+
+ /**
+ * The Apache Commons Net FTP file type.
+ */
+ private final int value;
+
+ /**
+ * Constructs a file type.
+ *
+ * @param fileType
+ * The Apache Commons Net FTP file type.
+ */
+ private FtpFileType(final int fileType)
+ {
+ this.value = fileType;
+ }
+
+ /**
+ * Gets the Apache Commons Net FTP file type.
+ *
+ * @return The Apache Commons Net FTP file type.
+ */
+ int getValue()
+ {
+ return this.value;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpRandomAccessContent.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpRandomAccessContent.java
new file mode 100644
index 0000000..6fc4db6
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpRandomAccessContent.java
@@ -0,0 +1,150 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ftp;
+
+import java.io.DataInputStream;
+import java.io.FilterInputStream;
+import java.io.IOException;
+
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.provider.AbstractRandomAccessStreamContent;
+import org.apache.commons.vfs2.util.RandomAccessMode;
+
+/**
+ * Implements FTP stream-based random access.
+ */
+class FtpRandomAccessContent extends AbstractRandomAccessStreamContent
+{
+ protected long filePointer;
+
+ private final FtpFileObject fileObject;
+ private DataInputStream dis;
+ private FtpFileObject.FtpInputStream mis;
+
+ FtpRandomAccessContent(final FtpFileObject fileObject, final RandomAccessMode mode)
+ {
+ super(mode);
+
+ this.fileObject = fileObject;
+ // fileSystem = (FtpFileSystem) this.fileObject.getFileSystem();
+ }
+
+ @Override
+ public long getFilePointer() throws IOException
+ {
+ return filePointer;
+ }
+
+ @Override
+ public void seek(final long pos) throws IOException
+ {
+ if (pos == filePointer)
+ {
+ // no change
+ return;
+ }
+
+ if (pos < 0)
+ {
+ throw new FileSystemException("vfs.provider/random-access-invalid-position.error",
+ Long.valueOf(pos));
+ }
+ if (dis != null)
+ {
+ close();
+ }
+
+ filePointer = pos;
+ }
+
+ @Override
+ protected DataInputStream getDataInputStream() throws IOException
+ {
+ if (dis != null)
+ {
+ return dis;
+ }
+
+ // FtpClient client = fileSystem.getClient();
+ mis = fileObject.getInputStream(filePointer);
+ dis = new DataInputStream(new FilterInputStream(mis)
+ {
+ @Override
+ public int read() throws IOException
+ {
+ final int ret = super.read();
+ if (ret > -1)
+ {
+ filePointer++;
+ }
+ return ret;
+ }
+
+ @Override
+ public int read(final byte[] b) throws IOException
+ {
+ final int ret = super.read(b);
+ if (ret > -1)
+ {
+ filePointer += ret;
+ }
+ return ret;
+ }
+
+ @Override
+ public int read(final byte[] b, final int off, final int len) throws IOException
+ {
+ final int ret = super.read(b, off, len);
+ if (ret > -1)
+ {
+ filePointer += ret;
+ }
+ return ret;
+ }
+
+ @Override
+ public void close() throws IOException
+ {
+ FtpRandomAccessContent.this.close();
+ }
+ });
+
+ return dis;
+ }
+
+
+ @Override
+ public void close() throws IOException
+ {
+ if (dis != null)
+ {
+ mis.abort();
+
+ // this is to avoid recursive close
+ final DataInputStream oldDis = dis;
+ dis = null;
+ oldDis.close();
+ mis = null;
+ }
+ }
+
+ @Override
+ public long length() throws IOException
+ {
+ return fileObject.getContent().getSize();
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/package.html
new file mode 100644
index 0000000..6035477
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftp/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>The FTP File Provider.</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsClientFactory.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsClientFactory.java
new file mode 100644
index 0000000..4662a50
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsClientFactory.java
@@ -0,0 +1,119 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ftps;
+
+
+import java.io.IOException;
+
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.SSLException;
+import javax.net.ssl.TrustManager;
+
+import org.apache.commons.net.ftp.FTPSClient;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.ftp.FtpClientFactory;
+
+/**
+ * Create FTPSClient instances.
+ *
+ * @since 2.0
+ */
+public final class FtpsClientFactory
+{
+ private FtpsClientFactory()
+ {
+ }
+
+ /**
+ * Creates a new connection to the server.
+ * @param hostname The host name.
+ * @param port The port.
+ * @param username The user name for authentication.
+ * @param password The user's password.
+ * @param workingDirectory The directory to use.
+ * @param fileSystemOptions The FileSystemOptions.
+ * @return The FTPSClient.
+ * @throws FileSystemException if an error occurs.
+ */
+ public static FTPSClient createConnection(final String hostname, final int port, final char[] username,
+ final char[] password, final String workingDirectory,
+ final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ final FtpsConnectionFactory factory = new FtpsConnectionFactory(FtpsFileSystemConfigBuilder.getInstance());
+ return factory.createConnection(hostname, port, username, password, workingDirectory, fileSystemOptions);
+ }
+
+ /** Connection Factory for FTPS case. */
+ private static final class FtpsConnectionFactory
+ extends FtpClientFactory.ConnectionFactory<FTPSClient, FtpsFileSystemConfigBuilder>
+ {
+
+ private FtpsConnectionFactory(final FtpsFileSystemConfigBuilder builder)
+ {
+ super(builder);
+ }
+
+ @Override
+ protected FTPSClient createClient(final FileSystemOptions fileSystemOptions) throws FileSystemException
+ {
+ final FTPSClient client;
+ if (builder.getFtpsMode(fileSystemOptions) == FtpsMode.IMPLICIT)
+ {
+ client = new FTPSClient(true);
+ }
+ else
+ {
+ client = new FTPSClient();
+ }
+
+ final TrustManager trustManager = builder.getTrustManager(fileSystemOptions);
+ if (trustManager != null)
+ {
+ client.setTrustManager(trustManager);
+ }
+
+ final KeyManager keyManager = builder.getKeyManager(fileSystemOptions);
+ if (keyManager != null)
+ {
+ client.setKeyManager(keyManager);
+ }
+ return client;
+ }
+
+ @Override
+ protected void setupOpenConnection(final FTPSClient client, final FileSystemOptions fileSystemOptions)
+ throws IOException
+ {
+ final FtpsDataChannelProtectionLevel level = builder.getDataChannelProtectionLevel(fileSystemOptions);
+ if (level != null)
+ {
+ // '0' means streaming, that's what we do!
+ try
+ {
+ client.execPBSZ(0);
+ client.execPROT(level.name());
+ }
+ catch (final SSLException e)
+ {
+ throw new FileSystemException("vfs.provider.ftps/data-channel.level", e, level.toString());
+ }
+ }
+ }
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsClientWrapper.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsClientWrapper.java
new file mode 100644
index 0000000..daa3d08
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsClientWrapper.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ftps;
+
+
+import org.apache.commons.net.ftp.FTPClient;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.UserAuthenticationData;
+import org.apache.commons.vfs2.provider.GenericFileName;
+import org.apache.commons.vfs2.provider.ftp.FTPClientWrapper;
+import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
+
+
+/**
+ * A wrapper to the FTPSClient to allow automatic reconnect on connection loss.
+ * <p>
+ * The only difference to the {@link FTPClientWrapper} is the creation of a {@link FTPSClient}
+ * instead of a {@link FTPClient}.
+ *
+ * @since 2.0
+ */
+class FtpsClientWrapper extends FTPClientWrapper
+{
+ FtpsClientWrapper(final GenericFileName root, final FileSystemOptions fileSystemOptions) throws FileSystemException
+ {
+ super(root, fileSystemOptions);
+ }
+
+ @Override
+ protected FTPClient createClient(final GenericFileName rootName, final UserAuthenticationData authData)
+ throws FileSystemException
+ {
+ return FtpsClientFactory.createConnection(
+ rootName.getHostName(),
+ rootName.getPort(),
+ UserAuthenticatorUtils.getData(
+ authData, UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(rootName.getUserName())),
+ UserAuthenticatorUtils.getData(
+ authData, UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(rootName.getPassword())),
+ rootName.getPath(), getFileSystemOptions());
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsDataChannelProtectionLevel.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsDataChannelProtectionLevel.java
new file mode 100644
index 0000000..a13a52e
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsDataChannelProtectionLevel.java
@@ -0,0 +1,28 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ftps;
+
+/**
+ * Protection level of the data channel in a FTPS communication.
+ *
+ * @see <a href="http://tools.ietf.org/html/rfc2228#section-3">RFC 2228, section 3</a>
+ * @since 2.1
+ */
+public enum FtpsDataChannelProtectionLevel
+{
+ C, S, E, P
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsFileProvider.java
new file mode 100644
index 0000000..a5838d4
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsFileProvider.java
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ftps;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemConfigBuilder;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.GenericFileName;
+import org.apache.commons.vfs2.provider.ftp.FtpFileProvider;
+
+/**
+ * A provider for FTP file systems.
+ *
+ * NOTE: Most of the heavy lifting for FTPS is done by the org.apache.commons.vfs2.provider.ftp package since
+ * they both use commons-net package
+ *
+ * @since 2.0
+ */
+public class FtpsFileProvider extends FtpFileProvider
+{
+ public FtpsFileProvider()
+ {
+ super();
+ }
+
+ /**
+ * Creates the filesystem.
+ */
+ @Override
+ protected FileSystem doCreateFileSystem(final FileName name, final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ // Create the file system
+ final GenericFileName rootName = (GenericFileName) name;
+
+ final FtpsClientWrapper ftpClient = new FtpsClientWrapper(rootName, fileSystemOptions);
+
+ return new FtpsFileSystem(rootName, ftpClient, fileSystemOptions);
+ }
+
+ @Override
+ public FileSystemConfigBuilder getConfigBuilder()
+ {
+ return FtpsFileSystemConfigBuilder.getInstance();
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsFileSystem.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsFileSystem.java
new file mode 100644
index 0000000..8b53701
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsFileSystem.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ftps;
+
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.GenericFileName;
+import org.apache.commons.vfs2.provider.ftp.FtpClient;
+import org.apache.commons.vfs2.provider.ftp.FtpFileSystem;
+
+
+/**
+ * A FTPS file system.
+ *
+ * @since 2.1
+ */
+public class FtpsFileSystem extends FtpFileSystem
+{
+ /**
+ * Create a new FtpsFileSystem.
+ *
+ * @param rootName The root of the file system.
+ * @param ftpClient The FtpClient.
+ * @param fileSystemOptions The FileSystemOptions.
+ * @since 2.1
+ */
+ public FtpsFileSystem(
+ final GenericFileName rootName, final FtpClient ftpClient, final FileSystemOptions fileSystemOptions)
+ {
+ super(rootName, ftpClient, fileSystemOptions);
+ }
+
+ @Override
+ protected FtpsClientWrapper createWrapper() throws FileSystemException
+ {
+ return new FtpsClientWrapper((GenericFileName) getRoot().getName(), getFileSystemOptions());
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsFileSystemConfigBuilder.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsFileSystemConfigBuilder.java
new file mode 100644
index 0000000..61cd6c2
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsFileSystemConfigBuilder.java
@@ -0,0 +1,222 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ftps;
+
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.TrustManager;
+
+import org.apache.commons.net.util.TrustManagerUtils;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.ftp.FtpFileSystemConfigBuilder;
+
+/**
+ * The configuration builder for various FTPS configuration options.
+ *
+ * @since 2.0
+ */
+public final class FtpsFileSystemConfigBuilder extends FtpFileSystemConfigBuilder
+{
+ private static final String _PREFIX = FtpsFileSystemConfigBuilder.class.getName();
+
+ private static final FtpsFileSystemConfigBuilder BUILDER = new FtpsFileSystemConfigBuilder();
+
+ private static final String FTPS_MODE = _PREFIX + ".FTPS_MODE";
+ private static final String PROT = _PREFIX + ".PROT";
+ private static final String KEY_MANAGER = _PREFIX + ".KEY_MANAGER";
+ private static final String TRUST_MANAGER = _PREFIX + ".TRUST_MANAGER";
+
+ private FtpsFileSystemConfigBuilder()
+ {
+ super("ftps.");
+ }
+
+ /**
+ * Gets the singleton builder.
+ *
+ * @return the singleton builder.
+ */
+ public static FtpsFileSystemConfigBuilder getInstance()
+ {
+ return BUILDER;
+ }
+
+ /**
+ * Set FTPS mode, either "implicit" or "explicit".
+ *
+ * <p>Note, that implicit mode is not standardized and considered as deprecated. Some unit tests for VFS fail with
+ * implicit mode and it is not yet clear if its a problem with Commons VFS/Commons Net or our test server Apache
+ * FTP/SSHD.</p>
+ *
+ * @param opts The FileSystemOptions.
+ * @param ftpsMode The mode to establish a FTPS connection.
+ * @see <a href="http://en.wikipedia.org/wiki/FTPS#Implicit">Wikipedia: FTPS/Implicit</a>
+ * @since 2.1
+ */
+ public void setFtpsMode(final FileSystemOptions opts, final FtpsMode ftpsMode)
+ {
+ setParam(opts, FTPS_MODE, ftpsMode);
+ }
+
+ /**
+ * Return the FTPS mode. Defaults to "explicit" if not defined.
+ *
+ * @param opts The FileSystemOptions.
+ * @return The file type.
+ * @see #setFtpsType
+ */
+ public FtpsMode getFtpsMode(final FileSystemOptions opts)
+ {
+ return getEnum(FtpsMode.class, opts, FTPS_MODE, FtpsMode.EXPLICIT);
+ }
+
+ /**
+ * Set FTPS type, either "implicit" or "explicit".
+ * <p>
+ * Note, that implicit mode is not standardized and considered as deprecated. Some unit tests for VFS fail with
+ * implicit mode and it is not yet clear if its a problem with Commons VFS/Commons Net or our test server Apache
+ * FTP/SSHD.
+ * </p>
+ *
+ * @param opts The FileSystemOptions.
+ * @param ftpsType The file type.
+ * @see <a href="http://en.wikipedia.org/wiki/FTPS#Implicit">Wikipedia: FTPS/Implicit</a>
+ * @deprecated As of 2.1, use {@link #setFtpsMode(FileSystemOptions, FtpsMode)}
+ */
+ @Deprecated
+ public void setFtpsType(final FileSystemOptions opts, final String ftpsType)
+ {
+ final FtpsMode mode;
+ if (ftpsType != null)
+ {
+ mode = FtpsMode.valueOf(ftpsType.toUpperCase());
+ if (mode == null)
+ {
+ throw new IllegalArgumentException("Not a proper FTPS mode: " + ftpsType);
+ }
+ }
+ else
+ {
+ mode = null;
+ }
+ setFtpsMode(opts, mode);
+ }
+
+ /**
+ * Return the FTPS type. Defaults to "explicit" if not defined.
+ *
+ * @param opts The FileSystemOptions.
+ * @return The file type.
+ * @see #setFtpsType
+ * @deprecated As of 2.1, use {@link #getFtpsMode(FileSystemOptions)}
+ */
+ @Deprecated
+ public String getFtpsType(final FileSystemOptions opts)
+ {
+ return getFtpsMode(opts).name().toLowerCase();
+ }
+
+ /**
+ * Gets the data channel protection level (PROT).
+ *
+ * @param opts The FileSystemOptions.
+ * @return The PROT value.
+ * @see org.apache.commons.net.ftp.FTPSClient#execPROT(String)
+ * @since 2.1
+ */
+ public FtpsDataChannelProtectionLevel getDataChannelProtectionLevel(final FileSystemOptions opts)
+ {
+ return getEnum(FtpsDataChannelProtectionLevel.class, opts, PROT);
+ }
+
+ /**
+ * Sets the data channel protection level (PROT).
+ *
+ * @param opts The FileSystemOptions.
+ * @param prot The PROT value, {@code null} has no effect.
+ * @see org.apache.commons.net.ftp.FTPSClient#execPROT(String)
+ * @since 2.1
+ */
+ public void setDataChannelProtectionLevel(final FileSystemOptions opts, final FtpsDataChannelProtectionLevel prot)
+ {
+ setParam(opts, PROT, prot);
+ }
+
+ /**
+ * Gets the KeyManager used to provide a client-side certificate if the FTPS server requests it.
+ *
+ * @param opts The FileSystemOptions.
+ * @return the key manager instance or {@code null}
+ * @see org.apache.commons.net.ftp.FTPSClient#setKeyManager(KeyManager)
+ * @since 2.1
+ */
+ public KeyManager getKeyManager(final FileSystemOptions opts)
+ {
+ return (KeyManager) getParam(opts, KEY_MANAGER);
+ }
+
+ /**
+ * Sets the KeyManager used to provide a client-side certificate if the FTPS server requests it.
+ *
+ * @param opts The FileSystemOptions.
+ * @param keyManager The key manager instance.
+ * @see org.apache.commons.net.ftp.FTPSClient#setKeyManager(KeyManager)
+ * @since 2.1
+ */
+ public void setKeyManager(final FileSystemOptions opts, final KeyManager keyManager)
+ {
+ setParam(opts, KEY_MANAGER, keyManager);
+ }
+
+ /**
+ * Gets the TrustManager that validates the FTPS server's certificate.
+ * <p>
+ * If the params do not contain the key for the trust manager, it will return a trust manger that simply checks this
+ * certificate for validity.
+ * </p>
+ *
+ * @param opts The FileSystemOptions.
+ * @return the trust manager instance or {@code null}
+ * @see org.apache.commons.net.ftp.FTPSClient#setTrustManager(TrustManager)
+ * @since 2.1
+ */
+ public TrustManager getTrustManager(final FileSystemOptions opts)
+ {
+ final TrustManager trustManager;
+ if (hasParam(opts, TRUST_MANAGER))
+ {
+ trustManager = (TrustManager) getParam(opts, TRUST_MANAGER);
+ }
+ else
+ {
+ trustManager = TrustManagerUtils.getValidateServerCertificateTrustManager();
+ }
+ return trustManager;
+ }
+
+ /**
+ * Sets the TrustManager that validates the FTPS server's certificate.
+ *
+ * @param opts The FileSystemOptions.
+ * @param trustManager The trust manager instance.
+ * @see org.apache.commons.net.ftp.FTPSClient#setTrustManager(TrustManager)
+ * @since 2.1
+ */
+ public void setTrustManager(final FileSystemOptions opts, final TrustManager trustManager)
+ {
+ setParam(opts, TRUST_MANAGER, trustManager);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsMode.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsMode.java
new file mode 100644
index 0000000..9f28a6d
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsMode.java
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ftps;
+
+/**
+ * Mode of the FTPS connection.
+ *
+ * <p>Note, that 'implicit' mode is not standardized and considered as deprecated. Some unit tests for VFS fail with
+ * 'implicit' mode and it is not yet clear if its a problem with Commons VFS/Commons Net or our test server Apache
+ * FTP/SSHD.</p>
+ *
+ * @see <a href="http://en.wikipedia.org/wiki/FTPS#Implicit">Wikipedia: FTPS/Implicit</a>
+ * @since 2.1
+ */
+public enum FtpsMode
+{
+ IMPLICIT, EXPLICIT
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/package.html
new file mode 100644
index 0000000..025c6a4
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ftps/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>The FTPS File Provider.</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/gzip/GzipFileObject.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/gzip/GzipFileObject.java
new file mode 100644
index 0000000..b1cb4ae
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/gzip/GzipFileObject.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.gzip;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.zip.GZIPInputStream;
+import java.util.zip.GZIPOutputStream;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.compressed.CompressedFileFileObject;
+import org.apache.commons.vfs2.provider.compressed.CompressedFileFileSystem;
+
+/**
+ * the gzip file.
+ */
+public class GzipFileObject extends CompressedFileFileObject<GzipFileSystem>
+{
+ /**
+ * Deprecated since 2.1.
+ *
+ * @deprecated Use {@link #GzipFileObject(AbstractFileName, FileObject, GzipFileSystem)} instead.
+ */
+ @Deprecated
+ protected GzipFileObject(final AbstractFileName name, final FileObject container, final CompressedFileFileSystem fs) {
+ super(name, container, cast(fs));
+ }
+
+ protected GzipFileObject(final AbstractFileName name, final FileObject container, final GzipFileSystem fs)
+ {
+ super(name, container, fs);
+ }
+
+ @Override
+ protected InputStream doGetInputStream() throws Exception
+ {
+ final InputStream is = getContainer().getContent().getInputStream();
+ return new GZIPInputStream(is);
+ }
+
+ @Override
+ protected OutputStream doGetOutputStream(final boolean bAppend) throws Exception
+ {
+ final OutputStream os = getContainer().getContent().getOutputStream(false);
+ return new GZIPOutputStream(os);
+ }
+
+ private static GzipFileSystem cast(CompressedFileFileSystem fs) {
+ if (fs instanceof GzipFileSystem) {
+ return (GzipFileSystem) fs;
+ }
+ throw new IllegalArgumentException("GzipFileObject expects an instance of GzipFileSystem");
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/gzip/GzipFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/gzip/GzipFileProvider.java
new file mode 100644
index 0000000..90a2327
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/gzip/GzipFileProvider.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.gzip;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.compressed.CompressedFileFileProvider;
+
+/**
+ * Provides access to the content of gzip compressed files.
+ */
+public class GzipFileProvider extends CompressedFileFileProvider
+{
+ /**
+ * Capabilities.
+ */
+ protected static final Collection<Capability> capabilities =
+ Collections.unmodifiableCollection(Arrays.asList(new Capability[]
+ {
+ Capability.GET_LAST_MODIFIED,
+ Capability.GET_TYPE,
+ Capability.LIST_CHILDREN,
+ Capability.WRITE_CONTENT,
+ Capability.READ_CONTENT,
+ Capability.URI,
+ Capability.COMPRESS
+ }));
+
+ public GzipFileProvider()
+ {
+ super();
+ }
+
+ @Override
+ protected FileSystem createFileSystem(final FileName name, final FileObject file,
+ final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ return new GzipFileSystem(name, file, fileSystemOptions);
+ }
+
+ @Override
+ public Collection<Capability> getCapabilities()
+ {
+ return capabilities;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/gzip/GzipFileSystem.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/gzip/GzipFileSystem.java
new file mode 100644
index 0000000..2f4f130
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/gzip/GzipFileSystem.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.gzip;
+
+import java.util.Collection;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.compressed.CompressedFileFileSystem;
+
+/**
+ * Filesytem to handle compressed files using the gzip method.
+ */
+public class GzipFileSystem extends CompressedFileFileSystem
+{
+ protected GzipFileSystem(final FileName rootName, final FileObject parentLayer,
+ final FileSystemOptions fileSystemOptions)
+ {
+ super(rootName, parentLayer, fileSystemOptions);
+ }
+
+ @Override
+ protected FileObject createFile(final AbstractFileName name) throws FileSystemException
+ {
+ return new GzipFileObject(name, getParentLayer(), this);
+ }
+
+ @Override
+ protected void addCapabilities(final Collection<Capability> caps)
+ {
+ caps.addAll(GzipFileProvider.capabilities);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/gzip/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/gzip/package.html
new file mode 100644
index 0000000..535b163
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/gzip/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>The GZIP File Provider</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/HdfsFileAttributes.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/HdfsFileAttributes.java
new file mode 100644
index 0000000..346ffcb
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/HdfsFileAttributes.java
@@ -0,0 +1,60 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.hdfs;
+
+/**
+ * HDFS file content attributes.
+ *
+ * @since 2.1
+ */
+public enum HdfsFileAttributes
+{
+ /**
+ * Last access time.
+ */
+ LAST_ACCESS_TIME,
+
+ /**
+ * Block size.
+ */
+ BLOCK_SIZE,
+
+ /**
+ * Group.
+ */
+ GROUP,
+
+ /**
+ * Owner.
+ */
+ OWNER,
+
+ /**
+ * Permissions.
+ */
+ PERMISSIONS,
+
+ /**
+ * Length.
+ */
+ LENGTH,
+
+ /**
+ * Modification time.
+ */
+ MODIFICATION_TIME;
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/HdfsFileContentInfoFactory.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/HdfsFileContentInfoFactory.java
new file mode 100644
index 0000000..f1ddfdd
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/HdfsFileContentInfoFactory.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.hdfs;
+
+import org.apache.commons.vfs2.FileContent;
+import org.apache.commons.vfs2.FileContentInfo;
+import org.apache.commons.vfs2.FileContentInfoFactory;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.impl.DefaultFileContentInfo;
+
+/**
+ * Creates FileContentInfo instances for HDFS.
+ *
+ * @since 2.1
+ */
+public class HdfsFileContentInfoFactory implements FileContentInfoFactory
+{
+ private static final String CONTENT = "text/plain";
+ private static final String ENCODING = "UTF-8";
+
+ /**
+ * Creates a FileContentInfo for a the given FileContent.
+ *
+ * @param fileContent
+ * Use this FileContent to create a matching FileContentInfo
+ * @return a FileContentInfo for the given FileContent with content set to "text/plain" and encoding set to "UTF-8"
+ * @throws FileSystemException
+ * when a problem occurs creating the FileContentInfo.
+ */
+ @Override
+ public FileContentInfo create(final FileContent fileContent) throws FileSystemException
+ {
+ return new DefaultFileContentInfo(CONTENT, ENCODING);
+ }
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/HdfsFileObject.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/HdfsFileObject.java
new file mode 100644
index 0000000..3d84d8c
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/HdfsFileObject.java
@@ -0,0 +1,311 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.hdfs;
+
+import java.io.FileNotFoundException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.commons.vfs2.FileNotFolderException;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.RandomAccessContent;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileObject;
+import org.apache.commons.vfs2.util.RandomAccessMode;
+import org.apache.hadoop.fs.FileStatus;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+
+/**
+ * A VFS representation of an HDFS file.
+ *
+ * @since 2.1
+ */
+public class HdfsFileObject extends AbstractFileObject<HdfsFileSystem>
+{
+ private final HdfsFileSystem fs;
+ private final FileSystem hdfs;
+ private final Path path;
+ private FileStatus stat;
+
+ /**
+ * Constructs a new HDFS FileObject
+ *
+ * @param name
+ * FileName
+ * @param fs
+ * HdfsFileSystem instance
+ * @param hdfs
+ * Hadoop FileSystem instance
+ * @param p
+ * Path to the file in HDFS
+ */
+ protected HdfsFileObject(final AbstractFileName name, final HdfsFileSystem fs, final FileSystem hdfs, final Path p)
+ {
+ super(name, fs);
+ this.fs = fs;
+ this.hdfs = hdfs;
+ this.path = p;
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#canRenameTo(org.apache.commons.vfs2.FileObject)
+ */
+ @Override
+ public boolean canRenameTo(final FileObject newfile)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doAttach()
+ */
+ @Override
+ protected void doAttach() throws Exception
+ {
+ try
+ {
+ this.stat = this.hdfs.getFileStatus(this.path);
+ }
+ catch (final FileNotFoundException e)
+ {
+ this.stat = null;
+ return;
+ }
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doGetAttributes()
+ */
+ @Override
+ protected Map<String, Object> doGetAttributes() throws Exception
+ {
+ if (null == this.stat)
+ {
+ return super.doGetAttributes();
+ }
+ else
+ {
+ final Map<String, Object> attrs = new HashMap<String, Object>();
+ attrs.put(HdfsFileAttributes.LAST_ACCESS_TIME.toString(), this.stat.getAccessTime());
+ attrs.put(HdfsFileAttributes.BLOCK_SIZE.toString(), this.stat.getBlockSize());
+ attrs.put(HdfsFileAttributes.GROUP.toString(), this.stat.getGroup());
+ attrs.put(HdfsFileAttributes.OWNER.toString(), this.stat.getOwner());
+ attrs.put(HdfsFileAttributes.PERMISSIONS.toString(), this.stat.getPermission().toString());
+ attrs.put(HdfsFileAttributes.LENGTH.toString(), this.stat.getLen());
+ attrs.put(HdfsFileAttributes.MODIFICATION_TIME.toString(), this.stat.getModificationTime());
+ return attrs;
+ }
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doGetContentSize()
+ */
+ @Override
+ protected long doGetContentSize() throws Exception
+ {
+ return stat.getLen();
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doGetInputStream()
+ */
+ @Override
+ protected InputStream doGetInputStream() throws Exception
+ {
+ return this.hdfs.open(this.path);
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doGetLastModifiedTime()
+ */
+ @Override
+ protected long doGetLastModifiedTime() throws Exception
+ {
+ if (null != this.stat)
+ {
+ return this.stat.getModificationTime();
+ }
+ else
+ {
+ return -1;
+ }
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doGetRandomAccessContent
+ * (org.apache.commons.vfs2.util.RandomAccessMode)
+ */
+ @Override
+ protected RandomAccessContent doGetRandomAccessContent(final RandomAccessMode mode) throws Exception
+ {
+ if (mode.equals(RandomAccessMode.READWRITE))
+ {
+ throw new UnsupportedOperationException();
+ }
+ return new HdfsRandomAccessContent(this.path, this.hdfs);
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doGetType()
+ */
+ @Override
+ protected FileType doGetType() throws Exception
+ {
+ try
+ {
+ doAttach();
+ if (null == stat)
+ {
+ return FileType.IMAGINARY;
+ }
+ if (stat.isDir())
+ {
+ return FileType.FOLDER;
+ }
+ else
+ {
+ return FileType.FILE;
+ }
+ }
+ catch (final FileNotFoundException fnfe)
+ {
+ return FileType.IMAGINARY;
+ }
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doIsHidden()
+ */
+ @Override
+ protected boolean doIsHidden() throws Exception
+ {
+ return false;
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doIsReadable()
+ */
+ @Override
+ protected boolean doIsReadable() throws Exception
+ {
+ return true;
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doIsWriteable()
+ */
+ @Override
+ protected boolean doIsWriteable() throws Exception
+ {
+ return false;
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doListChildren()
+ */
+ @Override
+ protected String[] doListChildren() throws Exception
+ {
+ if (this.doGetType() != FileType.FOLDER)
+ {
+ throw new FileNotFolderException(this);
+ }
+
+ final FileStatus[] files = this.hdfs.listStatus(this.path);
+ final String[] children = new String[files.length];
+ int i = 0;
+ for (final FileStatus status : files)
+ {
+ children[i++] = status.getPath().getName();
+ }
+ return children;
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doListChildrenResolved()
+ */
+ @Override
+ protected FileObject[] doListChildrenResolved() throws Exception
+ {
+ if (this.doGetType() != FileType.FOLDER)
+ {
+ return null;
+ }
+ final String[] children = doListChildren();
+ final FileObject[] fo = new FileObject[children.length];
+ for (int i = 0; i < children.length; i++)
+ {
+ final Path p = new Path(this.path, children[i]);
+ fo[i] = this.fs.resolveFile(p.toUri().toString());
+ }
+ return fo;
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doRemoveAttribute(java.lang.String)
+ */
+ @Override
+ protected void doRemoveAttribute(final String attrName) throws Exception
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doSetAttribute(java.lang.String, java.lang.Object)
+ */
+ @Override
+ protected void doSetAttribute(final String attrName, final Object value) throws Exception
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doSetLastModifiedTime(long)
+ */
+ @Override
+ protected boolean doSetLastModifiedTime(final long modtime) throws Exception
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#exists()
+ * @return boolean true if file exists, false if not
+ */
+ @Override
+ public boolean exists() throws FileSystemException
+ {
+ try
+ {
+ doAttach();
+ return this.stat != null;
+ }
+ catch (final FileNotFoundException fne)
+ {
+ return false;
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("Unable to check existance ", e);
+ }
+ }
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/HdfsFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/HdfsFileProvider.java
new file mode 100644
index 0000000..ace7337
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/HdfsFileProvider.java
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.hdfs;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemConfigBuilder;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider;
+import org.apache.commons.vfs2.provider.http.HttpFileNameParser;
+
+/**
+ * FileProvider for HDFS files.
+ *
+ * @since 2.1
+ */
+public class HdfsFileProvider extends AbstractOriginatingFileProvider
+{
+ static final Collection<Capability> CAPABILITIES = Collections.unmodifiableCollection(Arrays
+ .asList(new Capability[]
+ {
+ Capability.GET_TYPE,
+ Capability.READ_CONTENT,
+ Capability.URI,
+ Capability.GET_LAST_MODIFIED,
+ Capability.ATTRIBUTES,
+ Capability.RANDOM_ACCESS_READ,
+ Capability.DIRECTORY_READ_CONTENT,
+ Capability.LIST_CHILDREN }));
+
+ /**
+ * Constructs a new HdfsFileProvider.
+ */
+ public HdfsFileProvider()
+ {
+ super();
+ this.setFileNameParser(HttpFileNameParser.getInstance());
+ }
+
+ /**
+ * Create a new HdfsFileSystem instance.
+ * @param rootName Name of the root file.
+ * @param fileSystemOptions Configuration options for this instance.
+ * @throws FileSystemException if error occurred.
+ */
+ @Override
+ protected FileSystem doCreateFileSystem(final FileName rootName, final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ return new HdfsFileSystem(rootName, fileSystemOptions);
+ }
+
+ /**
+ * Get Capabilities of HdfsFileSystem.
+ * @return The capabilities (unmodifiable).
+ */
+ @Override
+ public Collection<Capability> getCapabilities()
+ {
+ return CAPABILITIES;
+ }
+
+ /**
+ * Return config builder.
+ * @return A config builder for HdfsFileSystems.
+ * @see org.apache.commons.vfs2.provider.AbstractFileProvider#getConfigBuilder()
+ */
+ @Override
+ public FileSystemConfigBuilder getConfigBuilder()
+ {
+ return HdfsFileSystemConfigBuilder.getInstance();
+ }
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/HdfsFileSystem.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/HdfsFileSystem.java
new file mode 100644
index 0000000..2c35d0b
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/HdfsFileSystem.java
@@ -0,0 +1,212 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.hdfs;
+
+import java.io.InputStream;
+import java.io.IOException;
+import java.io.UnsupportedEncodingException;
+import java.net.URL;
+import java.net.URLDecoder;
+import java.util.Collection;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.vfs2.CacheStrategy;
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileSystem;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+
+/**
+ * A VFS FileSystem that interacts with HDFS.
+ *
+ * @since 2.1
+ */
+public class HdfsFileSystem extends AbstractFileSystem
+{
+ private static final Log log = LogFactory.getLog(HdfsFileSystem.class);
+
+ private FileSystem fs;
+
+ /**
+ * Construct file system.
+ *
+ * @param rootName Name of the root directory of this file system.
+ * @param fileSystemOptions options for this file system instance.
+ */
+ protected HdfsFileSystem(final FileName rootName, final FileSystemOptions fileSystemOptions)
+ {
+ super(rootName, null, fileSystemOptions);
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.provider.AbstractFileSystem#addCapabilities(Collection)
+ */
+ @Override
+ protected void addCapabilities(final Collection<Capability> capabilities)
+ {
+ capabilities.addAll(HdfsFileProvider.CAPABILITIES);
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.provider.AbstractFileSystem#close()
+ */
+ @Override
+ public void close()
+ {
+ try
+ {
+ if (null != fs)
+ {
+ fs.close();
+ }
+ }
+ catch (final IOException e)
+ {
+ throw new RuntimeException("Error closing HDFS client", e);
+ }
+ super.close();
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.provider.AbstractFileSystem#createFile(AbstractFileName)
+ */
+ @Override
+ protected FileObject createFile(final AbstractFileName name) throws Exception
+ {
+ throw new FileSystemException("Operation not supported");
+ }
+
+ /**
+ * Resolve FileName into FileObject.
+ * @param name The name of a file on the HdfsFileSystem.
+ * @return resolved FileObject.
+ * @throws FileSystemException if an error occurred.
+ */
+ @Override
+ public FileObject resolveFile(final FileName name) throws FileSystemException
+ {
+ synchronized (this)
+ {
+ if (this.fs == null)
+ {
+ final String hdfsUri = name.getRootURI();
+ final HdfsFileSystemConfigBuilder builder = HdfsFileSystemConfigBuilder.getInstance();
+ final FileSystemOptions options = getFileSystemOptions();
+ final String[] configNames = builder.getConfigNames(options);
+ final Path[] configPaths = builder.getConfigPaths(options);
+ final URL[] configURLs = builder.getConfigURLs(options);
+ final InputStream configStream = builder.getConfigInputStream(options);
+ final Configuration configConfiguration = builder.getConfigConfiguration(options);
+
+ final Configuration conf = new Configuration(true);
+ conf.set(FileSystem.FS_DEFAULT_NAME_KEY, hdfsUri);
+
+ // Load any alternate configuration parameters that may have been specified
+ // no matter where they might come from
+ if (configNames != null)
+ {
+ for (String configName : configNames)
+ {
+ log.debug("Adding HDFS configuration resource: " + configName);
+ conf.addResource(configName);
+ }
+ }
+ if (configPaths != null)
+ {
+ for (Path path : configPaths)
+ {
+ log.debug("Adding HDFS configuration path: " + path);
+ conf.addResource(path);
+ }
+ }
+ if (configURLs != null)
+ {
+ for (URL url : configURLs)
+ {
+ log.debug("Adding HDFS configuration URL: " + url);
+ conf.addResource(url);
+ }
+ }
+ if (configStream != null)
+ {
+ log.debug("Adding HDFS configuration stream");
+ conf.addResource(configStream);
+ }
+ if (configConfiguration != null)
+ {
+ log.debug("Adding HDFS configuration object");
+ conf.addResource(configConfiguration);
+ }
+
+ try
+ {
+ fs = FileSystem.get(conf);
+ }
+ catch (final IOException e)
+ {
+ log.error("Error connecting to filesystem " + hdfsUri, e);
+ throw new FileSystemException("Error connecting to filesystem " + hdfsUri, e);
+ }
+ }
+ }
+
+ final boolean useCache = null != getContext().getFileSystemManager().getFilesCache();
+ FileObject file;
+ if (useCache)
+ {
+ file = this.getFileFromCache(name);
+ }
+ else
+ {
+ file = null;
+ }
+ if (null == file)
+ {
+ String path = null;
+ try
+ {
+ path = URLDecoder.decode(name.getPath(), "UTF-8");
+ }
+ catch (final UnsupportedEncodingException e)
+ {
+ path = name.getPath();
+ }
+ final Path filePath = new Path(path);
+ file = new HdfsFileObject((AbstractFileName) name, this, fs, filePath);
+ if (useCache)
+ {
+ this.putFileToCache(file);
+ }
+ }
+ /**
+ * resync the file information if requested
+ */
+ if (getFileSystemManager().getCacheStrategy().equals(CacheStrategy.ON_RESOLVE))
+ {
+ file.refresh();
+ }
+ return file;
+ }
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/HdfsFileSystemConfigBuilder.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/HdfsFileSystemConfigBuilder.java
new file mode 100644
index 0000000..5f1e12e
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/HdfsFileSystemConfigBuilder.java
@@ -0,0 +1,313 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.hdfs;
+
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.URL;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemConfigBuilder;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.Path;
+
+/**
+ * Configuration settings for the HdfsFileSystem.
+ *
+ * @since 2.1
+ */
+public final class HdfsFileSystemConfigBuilder extends FileSystemConfigBuilder
+{
+ private static final HdfsFileSystemConfigBuilder BUILDER = new HdfsFileSystemConfigBuilder();
+ private static final String KEY_CONFIG_NAMES = "configNames";
+ private static final String KEY_CONFIG_PATHS = "configPaths";
+ private static final String KEY_CONFIG_URLS = "configURLs";
+ private static final String KEY_CONFIG_STREAM = "configStream";
+ private static final String KEY_CONFIG_CONF = "configConf";
+
+ private HdfsFileSystemConfigBuilder()
+ {
+ super("hdfs.");
+ }
+
+ /**
+ * @return HdfsFileSystemConfigBuilder instance
+ */
+ public static HdfsFileSystemConfigBuilder getInstance()
+ {
+ return BUILDER;
+ }
+
+ /**
+ * @return HDFSFileSystem
+ */
+ @Override
+ protected Class<? extends FileSystem> getConfigClass()
+ {
+ return HdfsFileSystem.class;
+ }
+
+ /**
+ * Get names of alternate configuration resources.
+ *
+ * @return resource name list of alternate configurations or {@code null}.
+ * @param opts The FileSystemOptions.
+ * @see #setConfigName(FileSystemOptions, String)
+ */
+ public String[] getConfigNames(final FileSystemOptions opts)
+ {
+ String names = this.getString(opts, KEY_CONFIG_NAMES);
+ return names == null || names.isEmpty() ? null : names.split(",");
+ }
+
+ /**
+ * Sets the name of configuration resource to be loaded after the defaults.
+ * <p>
+ * Specifies the name of a config resource to override any specific HDFS settings.
+ * The property will be passed on to {@code org.apache.hadoop.conf.Configuration#addResource(String)}
+ * after the URL was set as the default name with: {@code Configuration#set(FileSystem.FS_DEFAULT_NAME_KEY, url)}.
+ * <p>
+ * One use for this is to set a different value for the {@code dfs.client.use.datanode.hostname}
+ * property in order to access HDFS files stored in an AWS installation (from outside their
+ * firewall). There are other possible uses too.
+ * <p>
+ * This method may be called multiple times and all the specified resources will be loaded
+ * in the order they were specified.
+ * <p>
+ * Note also, that if a list of names is provided, separated by commas ({@code ","}), that
+ * this will work the same as calling this method a number of times with just one name each.
+ *
+ * @param opts The FileSystemOptions to modify.
+ * @param name resource name of additional configuration or {@code null} to unset all the
+ * values set so far.
+ * @see #getConfigNames
+ */
+ public void setConfigName(final FileSystemOptions opts, final String name)
+ {
+ if (name == null || name.isEmpty())
+ {
+ this.setParam(opts, KEY_CONFIG_NAMES, null);
+ }
+ else
+ {
+ String previousNames = this.getString(opts, KEY_CONFIG_NAMES);
+ if (previousNames == null || previousNames.isEmpty())
+ {
+ this.setParam(opts, KEY_CONFIG_NAMES, name);
+ }
+ else
+ {
+ this.setParam(opts, KEY_CONFIG_NAMES, previousNames + "," + name);
+ }
+ }
+ }
+
+ /**
+ * Get paths of alternate configuration file system files.
+ *
+ * @return list of full paths of alternate configuration files or {@code null}.
+ * @param opts The FileSystemOptions.
+ * @see #setConfigPath(FileSystemOptions, Path)
+ */
+ public Path[] getConfigPaths(final FileSystemOptions opts)
+ {
+ String pathNames = this.getString(opts, KEY_CONFIG_PATHS);
+ if (pathNames == null || pathNames.isEmpty())
+ {
+ return null;
+ }
+ String[] paths = pathNames.split(",");
+ Path[] realPaths = new Path[paths.length];
+ for (int i = 0; i < paths.length; i++)
+ {
+ realPaths[i] = new Path(paths[i]);
+ }
+ return realPaths;
+ }
+
+ /**
+ * Sets the full path of configuration file to be loaded after the defaults.
+ * <p>
+ * Specifies the path of a local file system config file to override any specific HDFS settings.
+ * The property will be passed on to {@code org.apache.hadoop.conf.Configuration#addResource(Path)}
+ * after the URL was set as the default name with: {@code Configuration#set(FileSystem.FS_DEFAULT_NAME_KEY, url)}.
+ * <p>
+ * One use for this is to set a different value for the {@code dfs.client.use.datanode.hostname}
+ * property in order to access HDFS files stored in an AWS installation (from outside their
+ * firewall). There are other possible uses too.
+ * <p>
+ * This method may be called multiple times and all the specified resources will be loaded
+ * in the order they were specified.
+ *
+ * @param opts The FileSystemOptions to modify.
+ * @param path full path of additional configuration file (local file system) or {@code null}
+ * to unset all the path values set so far.
+ */
+ public void setConfigPath(final FileSystemOptions opts, final Path path)
+ {
+ if (path == null)
+ {
+ this.setParam(opts, KEY_CONFIG_PATHS, null);
+ }
+ else
+ {
+ String previousPathNames = this.getString(opts, KEY_CONFIG_PATHS);
+ if (previousPathNames == null || previousPathNames.isEmpty())
+ {
+ this.setParam(opts, KEY_CONFIG_PATHS, path.toString());
+ }
+ else
+ {
+ this.setParam(opts, KEY_CONFIG_PATHS, previousPathNames + "," + path.toString());
+ }
+ }
+ }
+
+ /**
+ * Get URLs of alternate configurations.
+ *
+ * @return list of alternate configuration URLs or {@code null}.
+ * @param opts The FileSystemOptions.
+ * @see #setConfigURL(FileSystemOptions, URL)
+ */
+ public URL[] getConfigURLs(final FileSystemOptions opts)
+ {
+ try
+ {
+ String urlNames = this.getString(opts, KEY_CONFIG_URLS);
+ if (urlNames == null || urlNames.isEmpty())
+ {
+ return null;
+ }
+ String[] urls = urlNames.split(",");
+ URL[] realURLs = new URL[urls.length];
+ for (int i = 0; i < urls.length; i++)
+ {
+ realURLs[i] = new URL(urls[i]);
+ }
+ return realURLs;
+ }
+ catch (MalformedURLException mue)
+ {
+ // This should never happen because we save it in the proper form
+ }
+ return null;
+ }
+
+ /**
+ * Sets the URL of configuration file to be loaded after the defaults.
+ * <p>
+ * Specifies the URL of a config file to override any specific HDFS settings.
+ * The property will be passed on to {@code org.apache.hadoop.conf.Configuration#addResource(URL)}
+ * after the URL was set as the default name with: {@code Configuration#set(FileSystem.FS_DEFAULT_NAME_KEY, url)}.
+ * <p>
+ * One use for this is to set a different value for the {@code dfs.client.use.datanode.hostname}
+ * property in order to access HDFS files stored in an AWS installation (from outside their
+ * firewall). There are other possible uses too.
+ * <p>
+ * This method may be called multiple times and all the specified resources will be loaded
+ * in the order they were specified.
+ *
+ * @param opts The FileSystemOptions to modify.
+ * @param url URL of additional configuration file or {@code null} to unset all the URL
+ * values set so far.
+ */
+ public void setConfigURL(final FileSystemOptions opts, final URL url)
+ {
+ if (url == null)
+ {
+ this.setParam(opts, KEY_CONFIG_URLS, null);
+ }
+ else
+ {
+ String previousURLNames = this.getString(opts, KEY_CONFIG_URLS);
+ if (previousURLNames == null || previousURLNames.isEmpty())
+ {
+ this.setParam(opts, KEY_CONFIG_URLS, url.toString());
+ }
+ else
+ {
+ this.setParam(opts, KEY_CONFIG_URLS, previousURLNames + "," + url.toString());
+ }
+ }
+ }
+
+ /**
+ * Get alternate configuration input stream.
+ *
+ * @return alternate configuration input stream or {@code null}.
+ * @param opts The FileSystemOptions.
+ * @see #setConfigInputStream(FileSystemOptions, InputStream)
+ */
+ public InputStream getConfigInputStream(final FileSystemOptions opts)
+ {
+ return (InputStream)this.getParam(opts, KEY_CONFIG_STREAM);
+ }
+
+ /**
+ * Sets the input stream of configuration file to be loaded after the defaults.
+ * <p>
+ * Specifies an input stream connected to a config file to override any specific HDFS settings.
+ * The property will be passed on to {@code org.apache.hadoop.conf.Configuration#addResource(InputStream)}
+ * after the URL was set as the default name with: {@code Configuration#set(FileSystem.FS_DEFAULT_NAME_KEY, url)}.
+ * <p>
+ * One use for this is to set a different value for the {@code dfs.client.use.datanode.hostname}
+ * property in order to access HDFS files stored in an AWS installation (from outside their
+ * firewall). There are other possible uses too.
+ *
+ * @param opts The FileSystemOptions to modify.
+ * @param inputStream input stream of additional configuration file or {@code null} to unset
+ * the configuration input stream previously set up.
+ */
+ public void setConfigInputStream(final FileSystemOptions opts, final InputStream inputStream)
+ {
+ this.setParam(opts, KEY_CONFIG_STREAM, inputStream);
+ }
+
+ /**
+ * Get alternate configuration object.
+ *
+ * @return alternate configuration object or {@code null}.
+ * @param opts The FileSystemOptions.
+ * @see #setConfigConfiguration(FileSystemOptions, Configuration)
+ */
+ public Configuration getConfigConfiguration(final FileSystemOptions opts)
+ {
+ return (Configuration)this.getParam(opts, KEY_CONFIG_CONF);
+ }
+
+ /**
+ * Sets the configuration object to be loaded after the defaults.
+ * <p>
+ * Specifies an already initialized configuration object to override any specific HDFS settings.
+ * The property will be passed on to {@code org.apache.hadoop.conf.Configuration#addResource(Configuration)}
+ * after the URL was set as the default name with: {@code Configuration#set(FileSystem.FS_DEFAULT_NAME_KEY, url)}.
+ * <p>
+ * One use for this is to set a different value for the {@code dfs.client.use.datanode.hostname}
+ * property in order to access HDFS files stored in an AWS installation (from outside their
+ * firewall). There are other possible uses too.
+ *
+ * @param opts The FileSystemOptions to modify.
+ * @param configuration additional configuration object or {@code null} to unset any configuration
+ * object previously set.
+ */
+ public void setConfigConfiguration(final FileSystemOptions opts, final Configuration configuration)
+ {
+ this.setParam(opts, KEY_CONFIG_CONF, configuration);
+ }
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/HdfsRandomAccessContent.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/HdfsRandomAccessContent.java
new file mode 100644
index 0000000..0e43fd3
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/HdfsRandomAccessContent.java
@@ -0,0 +1,245 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.hdfs;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.apache.commons.vfs2.provider.AbstractRandomAccessContent;
+import org.apache.commons.vfs2.util.RandomAccessMode;
+import org.apache.hadoop.fs.FSDataInputStream;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+
+/**
+ * Provides random access to content in an HdfsFileObject. Currently this only supports read operations. All write
+ * operations throw an {@link UnsupportedOperationException}.
+ *
+ * @since 2.1
+ */
+public class HdfsRandomAccessContent extends AbstractRandomAccessContent
+{
+ private final FSDataInputStream fis;
+ private final FileSystem fs;
+ private final Path path;
+
+ /**
+ * Create random access content.
+ *
+ * @param path A Hadoop Path
+ * @param fs A Hadoop FileSystem
+ * @throws IOException when the path cannot be processed.
+ */
+ public HdfsRandomAccessContent(final Path path, final FileSystem fs) throws IOException
+ {
+ super(RandomAccessMode.READ);
+ this.fs = fs;
+ this.path = path;
+ this.fis = this.fs.open(this.path);
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.RandomAccessContent#close()
+ */
+ @Override
+ public void close() throws IOException
+ {
+ this.fis.close();
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.RandomAccessContent#getFilePointer()
+ */
+ @Override
+ public long getFilePointer() throws IOException
+ {
+ return this.fis.getPos();
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.RandomAccessContent#getInputStream()
+ */
+ @Override
+ public InputStream getInputStream() throws IOException
+ {
+ return this.fis;
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.RandomAccessContent#length()
+ */
+ @Override
+ public long length() throws IOException
+ {
+ return this.fs.getFileStatus(this.path).getLen();
+ }
+
+ /**
+ * @see java.io.DataInput#readBoolean()
+ */
+ @Override
+ public boolean readBoolean() throws IOException
+ {
+ return this.fis.readBoolean();
+ }
+
+ /**
+ * @see java.io.DataInput#readByte()
+ */
+ @Override
+ public byte readByte() throws IOException
+ {
+ return this.fis.readByte();
+ }
+
+ /**
+ * @see java.io.DataInput#readChar()
+ */
+ @Override
+ public char readChar() throws IOException
+ {
+ return this.fis.readChar();
+ }
+
+ /**
+ * @see java.io.DataInput#readDouble()
+ */
+ @Override
+ public double readDouble() throws IOException
+ {
+ return this.fis.readDouble();
+ }
+
+ /**
+ * @see java.io.DataInput#readFloat()
+ */
+ @Override
+ public float readFloat() throws IOException
+ {
+ return this.fis.readFloat();
+ }
+
+ /**
+ * @see java.io.DataInput#readFully(byte[])
+ */
+ @Override
+ public void readFully(final byte[] b) throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @see java.io.DataInput#readFully(byte[], int, int)
+ */
+ @Override
+ public void readFully(final byte[] b, final int off, final int len) throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @see java.io.DataInput#readInt()
+ */
+ @Override
+ public int readInt() throws IOException
+ {
+ return this.fis.readInt();
+ }
+
+ /**
+ * @see java.io.DataInput#readLine()
+ */
+ @Override
+ @SuppressWarnings("deprecation")
+ public String readLine() throws IOException
+ {
+ return this.fis.readLine();
+ }
+
+ /**
+ * @see java.io.DataInput#readLong()
+ */
+ @Override
+ public long readLong() throws IOException
+ {
+ return this.fis.readLong();
+ }
+
+ /**
+ * @see java.io.DataInput#readShort()
+ */
+ @Override
+ public short readShort() throws IOException
+ {
+ return this.fis.readShort();
+ }
+
+ /**
+ * @see java.io.DataInput#readUnsignedByte()
+ */
+ @Override
+ public int readUnsignedByte() throws IOException
+ {
+ return this.fis.readUnsignedByte();
+ }
+
+ /**
+ * @see java.io.DataInput#readUnsignedShort()
+ */
+ @Override
+ public int readUnsignedShort() throws IOException
+ {
+ return this.fis.readUnsignedShort();
+ }
+
+ /**
+ * @see java.io.DataInput#readUTF()
+ */
+ @Override
+ public String readUTF() throws IOException
+ {
+ return this.fis.readUTF();
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.RandomAccessContent#seek(long)
+ */
+ @Override
+ public void seek(final long pos) throws IOException
+ {
+ this.fis.seek(pos);
+ }
+
+ /**
+ * @see org.apache.commons.vfs2.RandomAccessContent#setLength(long)
+ */
+ @Override
+ public void setLength(final long newLength) throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ /**
+ * @see java.io.DataInput#skipBytes(int)
+ */
+ @Override
+ public int skipBytes(final int n) throws IOException
+ {
+ throw new UnsupportedOperationException();
+ }
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/package.html
new file mode 100644
index 0000000..8cbb34e
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/hdfs/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>The HDFS File Provider</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpClientFactory.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpClientFactory.java
new file mode 100644
index 0000000..847b299
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpClientFactory.java
@@ -0,0 +1,157 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.http;
+
+import org.apache.commons.httpclient.Cookie;
+import org.apache.commons.httpclient.HostConfiguration;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpConnectionManager;
+import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
+import org.apache.commons.httpclient.UsernamePasswordCredentials;
+import org.apache.commons.httpclient.auth.AuthScope;
+import org.apache.commons.httpclient.methods.HeadMethod;
+import org.apache.commons.httpclient.params.HttpClientParams;
+import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.UserAuthenticationData;
+import org.apache.commons.vfs2.UserAuthenticator;
+import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
+
+/**
+ * Create a HttpClient instance.
+ */
+public final class HttpClientFactory
+{
+ private HttpClientFactory()
+ {
+ }
+
+ public static HttpClient createConnection(final String scheme, final String hostname, final int port,
+ final String username, final String password,
+ final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ return createConnection(HttpFileSystemConfigBuilder.getInstance(), scheme, hostname, port,
+ username, password, fileSystemOptions);
+ }
+
+ /**
+ * Creates a new connection to the server.
+ * @param builder The HttpFileSystemConfigBuilder.
+ * @param scheme The protocol.
+ * @param hostname The hostname.
+ * @param port The port number.
+ * @param username The username.
+ * @param password The password
+ * @param fileSystemOptions The file system options.
+ * @return a new HttpClient connection.
+ * @throws FileSystemException if an error occurs.
+ * @since 2.0
+ */
+ public static HttpClient createConnection(final HttpFileSystemConfigBuilder builder, final String scheme,
+ final String hostname, final int port, final String username,
+ final String password, final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ HttpClient client;
+ try
+ {
+ final HttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
+ final HttpConnectionManagerParams connectionMgrParams = mgr.getParams();
+
+ client = new HttpClient(mgr);
+
+ final HostConfiguration config = new HostConfiguration();
+ config.setHost(hostname, port, scheme);
+
+ if (fileSystemOptions != null)
+ {
+ final String proxyHost = builder.getProxyHost(fileSystemOptions);
+ final int proxyPort = builder.getProxyPort(fileSystemOptions);
+
+ if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0)
+ {
+ config.setProxy(proxyHost, proxyPort);
+ }
+
+ final UserAuthenticator proxyAuth = builder.getProxyAuthenticator(fileSystemOptions);
+ if (proxyAuth != null)
+ {
+ final UserAuthenticationData authData = UserAuthenticatorUtils.authenticate(proxyAuth,
+ new UserAuthenticationData.Type[]
+ {
+ UserAuthenticationData.USERNAME,
+ UserAuthenticationData.PASSWORD
+ });
+
+ if (authData != null)
+ {
+ final UsernamePasswordCredentials proxyCreds =
+ new UsernamePasswordCredentials(
+ UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
+ UserAuthenticationData.USERNAME, null)),
+ UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
+ UserAuthenticationData.PASSWORD, null)));
+
+ final AuthScope scope = new AuthScope(proxyHost, AuthScope.ANY_PORT);
+ client.getState().setProxyCredentials(scope, proxyCreds);
+ }
+
+ if (builder.isPreemptiveAuth(fileSystemOptions))
+ {
+ final HttpClientParams httpClientParams = new HttpClientParams();
+ httpClientParams.setAuthenticationPreemptive(true);
+ client.setParams(httpClientParams);
+ }
+ }
+
+ final Cookie[] cookies = builder.getCookies(fileSystemOptions);
+ if (cookies != null)
+ {
+ client.getState().addCookies(cookies);
+ }
+ }
+ /**
+ * ConnectionManager set methods must be called after the host & port and proxy host & port
+ * are set in the HostConfiguration. They are all used as part of the key when HttpConnectionManagerParams
+ * tries to locate the host configuration.
+ */
+ connectionMgrParams.setMaxConnectionsPerHost(config, builder.getMaxConnectionsPerHost(fileSystemOptions));
+ connectionMgrParams.setMaxTotalConnections(builder.getMaxTotalConnections(fileSystemOptions));
+
+ connectionMgrParams.setConnectionTimeout(builder.getConnectionTimeout(fileSystemOptions));
+ connectionMgrParams.setSoTimeout(builder.getSoTimeout(fileSystemOptions));
+
+ client.setHostConfiguration(config);
+
+ if (username != null)
+ {
+ final UsernamePasswordCredentials creds =
+ new UsernamePasswordCredentials(username, password);
+ final AuthScope scope = new AuthScope(hostname, AuthScope.ANY_PORT);
+ client.getState().setCredentials(scope, creds);
+ }
+ }
+ catch (final Exception exc)
+ {
+ throw new FileSystemException("vfs.provider.http/connect.error", exc, hostname);
+ }
+
+ return client;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileContentInfoFactory.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileContentInfoFactory.java
new file mode 100644
index 0000000..d764384
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileContentInfoFactory.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.http;
+
+import java.io.IOException;
+
+import org.apache.commons.httpclient.Header;
+import org.apache.commons.httpclient.HeaderElement;
+import org.apache.commons.httpclient.methods.HeadMethod;
+import org.apache.commons.vfs2.FileContent;
+import org.apache.commons.vfs2.FileContentInfo;
+import org.apache.commons.vfs2.FileContentInfoFactory;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.impl.DefaultFileContentInfo;
+import org.apache.commons.vfs2.util.FileObjectUtils;
+
+/**
+ * Creates FileContentInfo instances for HTTP.
+ */
+public class HttpFileContentInfoFactory implements FileContentInfoFactory
+{
+ @Override
+ public FileContentInfo create(final FileContent fileContent) throws FileSystemException
+ {
+ final HttpFileObject httpFile = (HttpFileObject) FileObjectUtils.getAbstractFileObject(fileContent.getFile());
+
+ String contentType = null;
+ String contentEncoding = null;
+
+ HeadMethod headMethod;
+ try
+ {
+ headMethod = httpFile.getHeadMethod();
+ }
+ catch (final IOException e)
+ {
+ throw new FileSystemException(e);
+ }
+ final Header header = headMethod.getResponseHeader("content-type");
+ if (header != null)
+ {
+ final HeaderElement[] element = header.getElements();
+ if (element != null && element.length > 0)
+ {
+ contentType = element[0].getName();
+ }
+ }
+
+ contentEncoding = headMethod.getResponseCharSet();
+
+ return new DefaultFileContentInfo(contentType, contentEncoding);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileNameParser.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileNameParser.java
new file mode 100644
index 0000000..e1f73c2
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileNameParser.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.http;
+
+import org.apache.commons.vfs2.provider.FileNameParser;
+import org.apache.commons.vfs2.provider.URLFileNameParser;
+
+/**
+ * Implementation for http. set default port to 80
+ */
+public class HttpFileNameParser extends URLFileNameParser
+{
+ private static final int DEFAULT_PORT = 80;
+
+ private static final HttpFileNameParser INSTANCE = new HttpFileNameParser();
+
+ public HttpFileNameParser()
+ {
+ super(DEFAULT_PORT);
+ }
+
+ public static FileNameParser getInstance()
+ {
+ return INSTANCE;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileObject.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileObject.java
new file mode 100644
index 0000000..60ebd3b
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileObject.java
@@ -0,0 +1,285 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.http;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+
+import org.apache.commons.httpclient.Header;
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpMethod;
+import org.apache.commons.httpclient.URIException;
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.commons.httpclient.methods.HeadMethod;
+import org.apache.commons.httpclient.util.DateUtil;
+import org.apache.commons.httpclient.util.URIUtil;
+import org.apache.commons.vfs2.FileContentInfoFactory;
+import org.apache.commons.vfs2.FileNotFoundException;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.RandomAccessContent;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileObject;
+import org.apache.commons.vfs2.provider.URLFileName;
+import org.apache.commons.vfs2.util.MonitorInputStream;
+import org.apache.commons.vfs2.util.RandomAccessMode;
+
+/**
+ * A file object backed by Apache Commons HttpClient.
+ * <p>
+ * TODO - status codes.
+ *
+ * @param <FS> An {@link HttpFileSystem} subclass
+ */
+public class HttpFileObject<FS extends HttpFileSystem> extends AbstractFileObject<FS>
+{
+ /**
+ * An InputStream that cleans up the HTTP connection on close.
+ */
+ static class HttpInputStream extends MonitorInputStream
+ {
+ private final GetMethod method;
+
+ public HttpInputStream(final GetMethod method)
+ throws IOException
+ {
+ super(method.getResponseBodyAsStream());
+ this.method = method;
+ }
+
+ /**
+ * Called after the stream has been closed.
+ */
+ @Override
+ protected void onClose() throws IOException
+ {
+ method.releaseConnection();
+ }
+ }
+ private final String urlCharset;
+ private final String userAgent;
+ private final boolean followRedirect;
+
+ private HeadMethod method;
+
+ protected HttpFileObject(final AbstractFileName name, final FS fileSystem)
+ {
+ this(name, fileSystem, HttpFileSystemConfigBuilder.getInstance());
+ }
+
+ protected HttpFileObject(final AbstractFileName name, final FS fileSystem,
+ final HttpFileSystemConfigBuilder builder)
+ {
+ super(name, fileSystem);
+ final FileSystemOptions fileSystemOptions = fileSystem.getFileSystemOptions();
+ urlCharset = builder.getUrlCharset(fileSystemOptions);
+ userAgent = builder.getUserAgent(fileSystemOptions);
+ followRedirect = builder.getFollowRedirect(fileSystemOptions);
+ }
+
+ /**
+ * Detaches this file object from its file resource.
+ */
+ @Override
+ protected void doDetach() throws Exception
+ {
+ method = null;
+ }
+
+ /**
+ * Returns the size of the file content (in bytes).
+ */
+ @Override
+ protected long doGetContentSize() throws Exception
+ {
+ final Header header = method.getResponseHeader("content-length");
+ if (header == null)
+ {
+ // Assume 0 content-length
+ return 0;
+ }
+ return Long.parseLong(header.getValue());
+ }
+
+ /**
+ * Creates an input stream to read the file content from. Is only called
+ * if {@link #doGetType} returns {@link FileType#FILE}.
+ * <p>
+ * It is guaranteed that there are no open output streams for this file
+ * when this method is called.
+ * <p>
+ * The returned stream does not have to be buffered.
+ */
+ @Override
+ protected InputStream doGetInputStream() throws Exception
+ {
+ final GetMethod getMethod = new GetMethod();
+ setupMethod(getMethod);
+ final int status = getAbstractFileSystem().getClient().executeMethod(getMethod);
+ if (status == HttpURLConnection.HTTP_NOT_FOUND)
+ {
+ throw new FileNotFoundException(getName());
+ }
+ if (status != HttpURLConnection.HTTP_OK)
+ {
+ throw new FileSystemException("vfs.provider.http/get.error", getName(), Integer.valueOf(status));
+ }
+
+ return new HttpInputStream(getMethod);
+ }
+
+ /**
+ * Returns the last modified time of this file.
+ * <p>
+ * This implementation throws an exception.
+ */
+ @Override
+ protected long doGetLastModifiedTime() throws Exception
+ {
+ final Header header = method.getResponseHeader("last-modified");
+ if (header == null)
+ {
+ throw new FileSystemException("vfs.provider.http/last-modified.error", getName());
+ }
+ return DateUtil.parseDate(header.getValue()).getTime();
+ }
+
+ @Override
+ protected RandomAccessContent doGetRandomAccessContent(final RandomAccessMode mode) throws Exception
+ {
+ return new HttpRandomAccessContent(this, mode);
+ }
+
+ /**
+ * Determines the type of this file. Must not return null. The return
+ * value of this method is cached, so the implementation can be expensive.
+ */
+ @Override
+ protected FileType doGetType() throws Exception
+ {
+ // Use the HEAD method to probe the file.
+ final int status = this.getHeadMethod().getStatusCode();
+ if (status == HttpURLConnection.HTTP_OK
+ || status == HttpURLConnection.HTTP_BAD_METHOD /* method is bad, but resource exist */)
+ {
+ return FileType.FILE;
+ }
+ else if (status == HttpURLConnection.HTTP_NOT_FOUND
+ || status == HttpURLConnection.HTTP_GONE)
+ {
+ return FileType.IMAGINARY;
+ }
+ else
+ {
+ throw new FileSystemException("vfs.provider.http/head.error", getName(), Integer.valueOf(status));
+ }
+ }
+
+ @Override
+ protected boolean doIsWriteable() throws Exception
+ {
+ return false;
+ }
+
+ /**
+ * Lists the children of this file.
+ */
+ @Override
+ protected String[] doListChildren() throws Exception
+ {
+ throw new Exception("Not implemented.");
+ }
+
+ protected String encodePath(final String decodedPath) throws URIException
+ {
+ return URIUtil.encodePath(decodedPath);
+ }
+
+
+ @Override
+ protected FileContentInfoFactory getFileContentInfoFactory()
+ {
+ return new HttpFileContentInfoFactory();
+ }
+
+ protected boolean getFollowRedirect()
+ {
+ return followRedirect;
+ }
+
+ protected String getUserAgent()
+ {
+ return userAgent;
+ }
+
+ HeadMethod getHeadMethod() throws IOException
+ {
+ if (method != null)
+ {
+ return method;
+ }
+ method = new HeadMethod();
+ setupMethod(method);
+ final HttpClient client = getAbstractFileSystem().getClient();
+ client.executeMethod(method);
+ method.releaseConnection();
+ return method;
+ }
+
+ protected String getUrlCharset()
+ {
+ return urlCharset;
+ }
+
+ /**
+ * Prepares a HttpMethod object.
+ *
+ * @param method The object which gets prepared to access the file object.
+ * @throws FileSystemException if an error occurs.
+ * @throws URIException if path cannot be represented.
+ * @since 2.0 (was package)
+ */
+ protected void setupMethod(final HttpMethod method) throws FileSystemException, URIException
+ {
+ final String pathEncoded = ((URLFileName) getName()).getPathQueryEncoded(this.getUrlCharset());
+ method.setPath(pathEncoded);
+ method.setFollowRedirects(this.getFollowRedirect());
+ method.setRequestHeader("User-Agent", this.getUserAgent());
+ }
+
+ /*
+ protected Map doGetAttributes() throws Exception
+ {
+ TreeMap map = new TreeMap();
+
+ Header contentType = method.getResponseHeader("content-type");
+ if (contentType != null)
+ {
+ HeaderElement[] element = contentType.getValues();
+ if (element != null && element.length > 0)
+ {
+ map.put("content-type", element[0].getName());
+ }
+ }
+
+ map.put("content-encoding", method.getResponseCharSet());
+ return map;
+ }
+ */
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileProvider.java
new file mode 100644
index 0000000..2dce321
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileProvider.java
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.http;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemConfigBuilder;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.UserAuthenticationData;
+import org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider;
+import org.apache.commons.vfs2.provider.GenericFileName;
+import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
+
+/**
+ * An HTTP provider that uses commons-httpclient.
+ */
+public class HttpFileProvider
+ extends AbstractOriginatingFileProvider
+{
+ /** Authenticator information. */
+ public static final UserAuthenticationData.Type[] AUTHENTICATOR_TYPES = new UserAuthenticationData.Type[]
+ {
+ UserAuthenticationData.USERNAME, UserAuthenticationData.PASSWORD
+ };
+
+ static final Collection<Capability> capabilities = Collections.unmodifiableCollection(Arrays.asList(new Capability[]
+ {
+ Capability.GET_TYPE,
+ Capability.READ_CONTENT,
+ Capability.URI,
+ Capability.GET_LAST_MODIFIED,
+ Capability.ATTRIBUTES,
+ Capability.RANDOM_ACCESS_READ,
+ Capability.DIRECTORY_READ_CONTENT,
+ }));
+
+ /**
+ * Constructs a new provider.
+ */
+ public HttpFileProvider()
+ {
+ super();
+ setFileNameParser(HttpFileNameParser.getInstance());
+ }
+
+ /**
+ * Creates a {@link FileSystem}.
+ */
+ @Override
+ protected FileSystem doCreateFileSystem(final FileName name, final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ // Create the file system
+ final GenericFileName rootName = (GenericFileName) name;
+
+ UserAuthenticationData authData = null;
+ HttpClient httpClient;
+ try
+ {
+ authData = UserAuthenticatorUtils.authenticate(fileSystemOptions, AUTHENTICATOR_TYPES);
+
+ httpClient = HttpClientFactory.createConnection(
+ rootName.getScheme(),
+ rootName.getHostName(),
+ rootName.getPort(),
+ UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
+ UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(rootName.getUserName()))),
+ UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
+ UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(rootName.getPassword()))),
+ fileSystemOptions);
+ }
+ finally
+ {
+ UserAuthenticatorUtils.cleanup(authData);
+ }
+
+ return new HttpFileSystem(rootName, httpClient, fileSystemOptions);
+ }
+
+ @Override
+ public FileSystemConfigBuilder getConfigBuilder()
+ {
+ return HttpFileSystemConfigBuilder.getInstance();
+ }
+
+ @Override
+ public Collection<Capability> getCapabilities()
+ {
+ return capabilities;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileSystem.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileSystem.java
new file mode 100644
index 0000000..213c1d1
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileSystem.java
@@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.http;
+
+import java.util.Collection;
+
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.httpclient.HttpConnectionManager;
+import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileSystem;
+import org.apache.commons.vfs2.provider.GenericFileName;
+
+/**
+ * An HTTP file system.
+ */
+public class HttpFileSystem
+ extends AbstractFileSystem
+{
+ private final HttpClient client;
+
+ protected HttpFileSystem(final GenericFileName rootName, final HttpClient client,
+ final FileSystemOptions fileSystemOptions)
+ {
+ super(rootName, null, fileSystemOptions);
+ this.client = client;
+ }
+
+ /**
+ * Adds the capabilities of this file system.
+ */
+ @Override
+ protected void addCapabilities(final Collection<Capability> caps)
+ {
+ caps.addAll(HttpFileProvider.capabilities);
+ }
+
+ protected HttpClient getClient()
+ {
+ return client;
+ }
+
+ /** @since 2.0 */
+ @Override
+ public void closeCommunicationLink()
+ {
+ if (getClient() != null)
+ {
+ final HttpConnectionManager mgr = getClient().getHttpConnectionManager();
+ if (mgr instanceof MultiThreadedHttpConnectionManager)
+ {
+ ((MultiThreadedHttpConnectionManager) mgr).shutdown();
+ }
+ }
+ }
+
+ /**
+ * Creates a file object. This method is called only if the requested
+ * file is not cached.
+ */
+ @Override
+ protected FileObject createFile(final AbstractFileName name)
+ throws Exception
+ {
+ return new HttpFileObject(name, this);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileSystemConfigBuilder.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileSystemConfigBuilder.java
new file mode 100644
index 0000000..7e34eed
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileSystemConfigBuilder.java
@@ -0,0 +1,364 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.http;
+
+import org.apache.commons.httpclient.Cookie;
+import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemConfigBuilder;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.UserAuthenticator;
+
+/**
+ * Configuration options for HTTP.
+ */
+public class HttpFileSystemConfigBuilder extends FileSystemConfigBuilder
+{
+ protected static final String KEY_FOLLOW_REDIRECT = "followRedirect";
+
+ protected static final String KEY_USER_AGENT = "userAgent";
+
+ private static final HttpFileSystemConfigBuilder BUILDER = new HttpFileSystemConfigBuilder();
+
+ private static final int DEFAULT_MAX_HOST_CONNECTIONS = 5;
+
+ private static final int DEFAULT_MAX_CONNECTIONS = 50;
+
+ private static final int DEFAULT_CONNECTION_TIMEOUT = 0;
+
+ private static final int DEFAULT_SO_TIMEOUT = 0;
+
+ private static final boolean DEFAULT_FOLLOW_REDIRECT = true;
+
+ private static final String DEFAULT_USER_AGENT = "Jakarta-Commons-VFS";
+
+ private static final String KEY_PREEMPTIVE_AUTHENTICATION = "preemptiveAuth";
+
+ /**
+ * Create new config builder.
+ * @param prefix String for properties of this file system.
+ * @since 2.0
+ */
+ protected HttpFileSystemConfigBuilder(final String prefix)
+ {
+ super(prefix);
+ }
+
+ private HttpFileSystemConfigBuilder()
+ {
+ super("http.");
+ }
+
+ /**
+ * Gets the singleton builder.
+ *
+ * @return the singleton builder.
+ */
+ public static HttpFileSystemConfigBuilder getInstance()
+ {
+ return BUILDER;
+ }
+
+ /**
+ * Set the charset used for url encoding.<br>
+ *
+ * @param opts The FileSystem options.
+ * @param chaset the chaset
+ */
+ public void setUrlCharset(final FileSystemOptions opts, final String chaset)
+ {
+ setParam(opts, "urlCharset", chaset);
+ }
+
+ /**
+ * Set the charset used for url encoding.<br>
+ *
+ * @param opts The FileSystem options.
+ * @return the chaset
+ */
+ public String getUrlCharset(final FileSystemOptions opts)
+ {
+ return getString(opts, "urlCharset");
+ }
+
+ /**
+ * Set the proxy to use for http connection.<br>
+ * You have to set the ProxyPort too if you would like to have the proxy really used.
+ *
+ * @param opts The FileSystem options.
+ * @param proxyHost the host
+ * @see #setProxyPort
+ */
+ public void setProxyHost(final FileSystemOptions opts, final String proxyHost)
+ {
+ setParam(opts, "proxyHost", proxyHost);
+ }
+
+ /**
+ * Set the proxy-port to use for http connection.
+ * You have to set the ProxyHost too if you would like to have the proxy really used.
+ *
+ * @param opts The FileSystem options.
+ * @param proxyPort the port
+ * @see #setProxyHost
+ */
+ public void setProxyPort(final FileSystemOptions opts, final int proxyPort)
+ {
+ setParam(opts, "proxyPort", Integer.valueOf(proxyPort));
+ }
+
+ /**
+ * Get the proxy to use for http connection.
+ * You have to set the ProxyPort too if you would like to have the proxy really used.
+ *
+ * @param opts The FileSystem options.
+ * @return proxyHost
+ * @see #setProxyPort
+ */
+ public String getProxyHost(final FileSystemOptions opts)
+ {
+ return getString(opts, "proxyHost");
+ }
+
+ /**
+ * Get the proxy-port to use for http the connection.
+ * You have to set the ProxyHost too if you would like to have the proxy really used.
+ *
+ * @param opts The FileSystem options.
+ * @return proxyPort: the port number or 0 if it is not set
+ * @see #setProxyHost
+ */
+ public int getProxyPort(final FileSystemOptions opts)
+ {
+ return getInteger(opts, "proxyPort", 0);
+ }
+
+ /**
+ * Set the proxy authenticator where the system should get the credentials from.
+ * @param opts The FileSystem options.
+ * @param authenticator The UserAuthenticator.
+ */
+ public void setProxyAuthenticator(final FileSystemOptions opts, final UserAuthenticator authenticator)
+ {
+ setParam(opts, "proxyAuthenticator", authenticator);
+ }
+
+ /**
+ * Get the proxy authenticator where the system should get the credentials from.
+ * @param opts The FileSystem options.
+ * @return The UserAuthenticator.
+ */
+ public UserAuthenticator getProxyAuthenticator(final FileSystemOptions opts)
+ {
+ return (UserAuthenticator) getParam(opts, "proxyAuthenticator");
+ }
+
+ /**
+ * The cookies to add to the request.
+ * @param opts The FileSystem options.
+ * @param cookies An array of Cookies.
+ */
+ public void setCookies(final FileSystemOptions opts, final Cookie[] cookies)
+ {
+ setParam(opts, "cookies", cookies);
+ }
+
+ /**
+ * Sets whether to follow redirects for the connection.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @param redirect
+ * {@code true} to follow redirects, {@code false} not to.
+ * @see #setFollowRedirect
+ * @since 2.1
+ */
+ public void setFollowRedirect(final FileSystemOptions opts, final boolean redirect)
+ {
+ setParam(opts, KEY_FOLLOW_REDIRECT, redirect);
+ }
+
+ /**
+ * The cookies to add to the request.
+ * @param opts The FileSystem options.
+ * @return the Cookie array.
+ */
+ public Cookie[] getCookies(final FileSystemOptions opts)
+ {
+ return (Cookie[]) getParam(opts, "cookies");
+ }
+
+ /**
+ * Gets whether to follow redirects for the connection.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @return {@code true} to follow redirects, {@code false} not to.
+ * @see #setFollowRedirect
+ * @since 2.1
+ */
+ public boolean getFollowRedirect(final FileSystemOptions opts)
+ {
+ return getBoolean(opts, KEY_FOLLOW_REDIRECT, DEFAULT_FOLLOW_REDIRECT);
+ }
+
+ /**
+ * The maximum number of connections allowed.
+ * @param opts The FileSystem options.
+ * @param maxTotalConnections The maximum number of connections.
+ * @since 2.0
+ */
+ public void setMaxTotalConnections(final FileSystemOptions opts, final int maxTotalConnections)
+ {
+ setParam(opts, HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS, Integer.valueOf(maxTotalConnections));
+ }
+
+ /**
+ * Retrieve the maximum number of connections allowed.
+ * @param opts The FileSystemOptions.
+ * @return The maximum number of connections allowed.
+ * @since 2.0
+ */
+ public int getMaxTotalConnections(final FileSystemOptions opts)
+ {
+ return getInteger(opts, HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS, DEFAULT_MAX_CONNECTIONS);
+ }
+
+ /**
+ * The maximum number of connections allowed to any host.
+ * @param opts The FileSystem options.
+ * @param maxHostConnections The maximum number of connections to a host.
+ * @since 2.0
+ */
+ public void setMaxConnectionsPerHost(final FileSystemOptions opts, final int maxHostConnections)
+ {
+ setParam(opts, HttpConnectionManagerParams.MAX_HOST_CONNECTIONS, Integer.valueOf(maxHostConnections));
+ }
+
+ /**
+ * Retrieve the maximum number of connections allowed per host.
+ * @param opts The FileSystemOptions.
+ * @return The maximum number of connections allowed per host.
+ * @since 2.0
+ */
+ public int getMaxConnectionsPerHost(final FileSystemOptions opts)
+ {
+ return getInteger(opts, HttpConnectionManagerParams.MAX_HOST_CONNECTIONS, DEFAULT_MAX_HOST_CONNECTIONS);
+ }
+
+ /**
+ * Determines if the FileSystemOptions indicate that preemptive
+ * authentication is requested.
+ * @param opts The FileSystemOptions.
+ * @return true if preemptiveAuth is requested.
+ * @since 2.0
+ */
+ public boolean isPreemptiveAuth(final FileSystemOptions opts)
+ {
+ return getBoolean(opts, KEY_PREEMPTIVE_AUTHENTICATION, Boolean.FALSE).booleanValue();
+ }
+
+ /**
+ * Sets the given value for preemptive HTTP authentication (using BASIC) on the
+ * given FileSystemOptions object. Defaults to false if not set. It may be
+ * appropriate to set to true in cases when the resulting chattiness of the
+ * conversation outweighs any architectural desire to use a stronger authentication
+ * scheme than basic/preemptive.
+ * @param opts The FileSystemOptions.
+ * @param preemptiveAuth the desired setting; true=enabled and false=disabled.
+ */
+ public void setPreemptiveAuth(final FileSystemOptions opts, final boolean preemptiveAuth)
+ {
+ setParam(opts, KEY_PREEMPTIVE_AUTHENTICATION, Boolean.valueOf(preemptiveAuth));
+ }
+
+ /**
+ * The connection timeout.
+ *
+ * @param opts The FileSystem options.
+ * @param connectionTimeout The connection timeout.
+ * @since 2.1
+ */
+ public void setConnectionTimeout(final FileSystemOptions opts, final int connectionTimeout)
+ {
+ setParam(opts, HttpConnectionManagerParams.CONNECTION_TIMEOUT, Integer.valueOf(connectionTimeout));
+ }
+
+ /**
+ * Retrieve the connection timeout.
+ *
+ * @param opts The FileSystem options.
+ * @return The connection timeout.
+ * @since 2.1
+ */
+ public int getConnectionTimeout(final FileSystemOptions opts)
+ {
+ return getInteger(opts, HttpConnectionManagerParams.CONNECTION_TIMEOUT, DEFAULT_CONNECTION_TIMEOUT);
+ }
+
+ /**
+ * The socket timeout.
+ *
+ * @param opts The FileSystem options.
+ * @param soTimeout socket timeout.
+ * @since 2.1
+ */
+ public void setSoTimeout(final FileSystemOptions opts, final int soTimeout)
+ {
+ setParam(opts, HttpConnectionManagerParams.SO_TIMEOUT, Integer.valueOf(soTimeout));
+ }
+
+ /**
+ * Retrieve the socket timeout.
+ *
+ * @param opts The FileSystemOptions.
+ * @return The socket timeout.
+ * @since 2.1
+ */
+ public int getSoTimeout(final FileSystemOptions opts)
+ {
+ return getInteger(opts, HttpConnectionManagerParams.SO_TIMEOUT, DEFAULT_SO_TIMEOUT);
+ }
+
+ /**
+ * Assign the user agent to attach to the outgoing http methods
+ *
+ * @param userAgent User Agent String
+ */
+ public void setUserAgent(final FileSystemOptions opts, final String userAgent)
+ {
+ setParam(opts, "userAgent", userAgent);
+ }
+
+ /**
+ * Return the user agent string
+ *
+ * @return User provided User-Agent string, otherwise default of: Jakarta-Commons-VFS
+ */
+ public String getUserAgent(final FileSystemOptions opts)
+ {
+ final String userAgent = (String) getParam(opts, KEY_USER_AGENT);
+ return userAgent != null ? userAgent : DEFAULT_USER_AGENT;
+ }
+
+
+ @Override
+ protected Class<? extends FileSystem> getConfigClass()
+ {
+ return HttpFileSystem.class;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpRandomAccessContent.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpRandomAccessContent.java
new file mode 100644
index 0000000..ba79fba
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpRandomAccessContent.java
@@ -0,0 +1,168 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.http;
+
+import java.io.DataInputStream;
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.net.HttpURLConnection;
+
+import org.apache.commons.httpclient.methods.GetMethod;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.provider.AbstractRandomAccessStreamContent;
+import org.apache.commons.vfs2.util.MonitorInputStream;
+import org.apache.commons.vfs2.util.RandomAccessMode;
+
+/**
+ * RandomAccess content using HTTP.
+ */
+class HttpRandomAccessContent extends AbstractRandomAccessStreamContent
+{
+ protected long filePointer = 0;
+
+ private final HttpFileObject fileObject;
+ private final HttpFileSystem fileSystem;
+
+ private DataInputStream dis = null;
+ private MonitorInputStream mis = null;
+
+ HttpRandomAccessContent(final HttpFileObject fileObject, final RandomAccessMode mode)
+ {
+ super(mode);
+
+ this.fileObject = fileObject;
+ fileSystem = (HttpFileSystem) this.fileObject.getFileSystem();
+ }
+
+ @Override
+ public long getFilePointer() throws IOException
+ {
+ return filePointer;
+ }
+
+ @Override
+ public void seek(final long pos) throws IOException
+ {
+ if (pos == filePointer)
+ {
+ // no change
+ return;
+ }
+
+ if (pos < 0)
+ {
+ throw new FileSystemException("vfs.provider/random-access-invalid-position.error",
+ Long.valueOf(pos));
+ }
+ if (dis != null)
+ {
+ close();
+ }
+
+ filePointer = pos;
+ }
+
+ @Override
+ protected DataInputStream getDataInputStream() throws IOException
+ {
+ if (dis != null)
+ {
+ return dis;
+ }
+
+ final GetMethod getMethod = new GetMethod();
+ fileObject.setupMethod(getMethod);
+ getMethod.setRequestHeader("Range", "bytes=" + filePointer + "-");
+ final int status = fileSystem.getClient().executeMethod(getMethod);
+ if (status != HttpURLConnection.HTTP_PARTIAL && status != HttpURLConnection.HTTP_OK)
+ {
+ throw new FileSystemException("vfs.provider.http/get-range.error",
+ fileObject.getName(),
+ Long.valueOf(filePointer),
+ Integer.valueOf(status));
+ }
+
+ mis = new HttpFileObject.HttpInputStream(getMethod);
+ // If the range request was ignored
+ if (status == HttpURLConnection.HTTP_OK)
+ {
+ final long skipped = mis.skip(filePointer);
+ if (skipped != filePointer)
+ {
+ throw new FileSystemException("vfs.provider.http/get-range.error",
+ fileObject.getName(),
+ Long.valueOf(filePointer),
+ Integer.valueOf(status));
+ }
+ }
+ dis = new DataInputStream(new FilterInputStream(mis)
+ {
+ @Override
+ public int read() throws IOException
+ {
+ final int ret = super.read();
+ if (ret > -1)
+ {
+ filePointer++;
+ }
+ return ret;
+ }
+
+ @Override
+ public int read(final byte[] b) throws IOException
+ {
+ final int ret = super.read(b);
+ if (ret > -1)
+ {
+ filePointer += ret;
+ }
+ return ret;
+ }
+
+ @Override
+ public int read(final byte[] b, final int off, final int len) throws IOException
+ {
+ final int ret = super.read(b, off, len);
+ if (ret > -1)
+ {
+ filePointer += ret;
+ }
+ return ret;
+ }
+ });
+
+ return dis;
+ }
+
+
+ @Override
+ public void close() throws IOException
+ {
+ if (dis != null)
+ {
+ dis.close();
+ dis = null;
+ mis = null;
+ }
+ }
+
+ @Override
+ public long length() throws IOException
+ {
+ return fileObject.getContent().getSize();
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/package.html
new file mode 100644
index 0000000..242a994
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/http/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>The HTTP File Provider</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/https/HttpsFileNameParser.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/https/HttpsFileNameParser.java
new file mode 100644
index 0000000..0298968
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/https/HttpsFileNameParser.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.https;
+
+import org.apache.commons.vfs2.provider.FileNameParser;
+import org.apache.commons.vfs2.provider.URLFileNameParser;
+
+/**
+ * Implementation for https. set default port to 443.
+ */
+public class HttpsFileNameParser extends URLFileNameParser
+{
+ private static final int DEFAULT_PORT = 443;
+
+ private static final HttpsFileNameParser INSTANCE = new HttpsFileNameParser();
+
+ public HttpsFileNameParser()
+ {
+ super(DEFAULT_PORT);
+ }
+
+ public static FileNameParser getInstance()
+ {
+ return INSTANCE;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/https/HttpsFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/https/HttpsFileProvider.java
new file mode 100644
index 0000000..468f13e
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/https/HttpsFileProvider.java
@@ -0,0 +1,32 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.https;
+
+import org.apache.commons.vfs2.provider.http.HttpFileProvider;
+
+/**
+ * An HTTPS provider that uses commons-httpclient.
+ */
+public class HttpsFileProvider
+ extends HttpFileProvider
+{
+ public HttpsFileProvider()
+ {
+ super();
+ setFileNameParser(HttpsFileNameParser.getInstance());
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/https/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/https/package.html
new file mode 100644
index 0000000..8eb9429
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/https/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>The HTTPS File Provider</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/jar/JarFileObject.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/jar/JarFileObject.java
new file mode 100644
index 0000000..8bb22a5
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/jar/JarFileObject.java
@@ -0,0 +1,143 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.jar;
+
+import java.io.IOException;
+import java.security.cert.Certificate;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.Map.Entry;
+import java.util.jar.Attributes;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.jar.Manifest;
+import java.util.zip.ZipEntry;
+
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.zip.ZipFileObject;
+
+/**
+ * A file in a Jar file system.
+ */
+public class JarFileObject extends ZipFileObject
+{
+ private final JarFileSystem fs;
+
+ private Attributes attributes;
+
+ protected JarFileObject(final AbstractFileName name,
+ final ZipEntry entry,
+ final JarFileSystem fs,
+ final boolean zipExists) throws FileSystemException
+ {
+ super(name, entry, fs, zipExists);
+ this.fs = fs;
+
+ try
+ {
+ getAttributes(); // early get the attributes as the zip file might be closed
+ }
+ catch (final IOException e)
+ {
+ throw new FileSystemException(e);
+ }
+ }
+
+ /**
+ * Returns the Jar manifest.
+ */
+ Manifest getManifest() throws IOException
+ {
+ if (fs.getZipFile() == null)
+ {
+ return null;
+ }
+
+ return ((JarFile) fs.getZipFile()).getManifest();
+ }
+
+ /**
+ * Returns the attributes of this file.
+ */
+ Attributes getAttributes() throws IOException
+ {
+ if (attributes == null)
+ {
+ if (entry == null)
+ {
+ attributes = new Attributes(1);
+ }
+ else
+ {
+ attributes = ((JarEntry) entry).getAttributes();
+ if (attributes == null)
+ {
+ attributes = new Attributes(1);
+ }
+ }
+ }
+
+ return attributes;
+ }
+
+ /**
+ * Returns the value of an attribute.
+ */
+ @Override
+ protected Map<String, Object> doGetAttributes()
+ throws Exception
+ {
+ final Map<String, Object> attrs = new HashMap<String, Object>();
+
+ // Add the file system's attributes first
+ final JarFileSystem fs = (JarFileSystem) getFileSystem();
+ addAll(fs.getAttributes(), attrs);
+
+ // Add this file's attributes
+ addAll(getAttributes(), attrs);
+
+ return attrs;
+ }
+
+ /**
+ * Adds the source attributes to the destination map.
+ */
+ private void addAll(final Attributes src, final Map<String, Object> dest)
+ {
+ for (final Entry<Object, Object> entry : src.entrySet())
+ {
+ // final String name = entry.getKey().toString().toLowerCase();
+ final String name = entry.getKey().toString();
+ dest.put(name, entry.getValue());
+ }
+ }
+
+ /**
+ * Return the certificates of this JarEntry.
+ */
+ @Override
+ protected Certificate[] doGetCertificates()
+ {
+ if (entry == null)
+ {
+ return null;
+ }
+
+ return ((JarEntry) entry).getCertificates();
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/jar/JarFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/jar/JarFileProvider.java
new file mode 100644
index 0000000..08d8a73
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/jar/JarFileProvider.java
@@ -0,0 +1,88 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.jar;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.LayeredFileName;
+import org.apache.commons.vfs2.provider.zip.ZipFileProvider;
+
+/**
+ * A file system provider for Jar files. Provides read-only file
+ * systems. This provides access to Jar specific features like Signing and
+ * Manifest Attributes.
+ */
+public class JarFileProvider extends ZipFileProvider
+{
+ static final Collection<Capability> capabilities;
+
+ static
+ {
+ final Collection<Capability> combined = new ArrayList<Capability>();
+ combined.addAll(ZipFileProvider.capabilities);
+ combined.addAll(Arrays.asList(new Capability[]
+ {
+ Capability.ATTRIBUTES,
+ Capability.FS_ATTRIBUTES,
+ Capability.SIGNING,
+ Capability.MANIFEST_ATTRIBUTES,
+ Capability.VIRTUAL
+ }));
+ capabilities = Collections.unmodifiableCollection(combined);
+ }
+
+ public JarFileProvider()
+ {
+ super();
+ }
+
+ /**
+ * Creates a layered file system. This method is called if the file system
+ * is not cached.
+ *
+ * @param scheme The URI scheme.
+ * @param file The file to create the file system on top of.
+ * @return The file system.
+ */
+ @Override
+ protected FileSystem doCreateFileSystem(final String scheme,
+ final FileObject file,
+ final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ final AbstractFileName name =
+ new LayeredFileName(scheme, file.getName(), FileName.ROOT_PATH, FileType.FOLDER);
+ return new JarFileSystem(name, file, fileSystemOptions);
+ }
+
+ @Override
+ public Collection<Capability> getCapabilities()
+ {
+ return capabilities;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/jar/JarFileSystem.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/jar/JarFileSystem.java
new file mode 100644
index 0000000..4ed50ff
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/jar/JarFileSystem.java
@@ -0,0 +1,222 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.jar;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.Collection;
+import java.util.jar.Attributes;
+import java.util.jar.Attributes.Name;
+import java.util.jar.JarFile;
+import java.util.jar.Manifest;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.zip.ZipFileObject;
+import org.apache.commons.vfs2.provider.zip.ZipFileSystem;
+
+/**
+ * A read-only file system for Jar files.
+ */
+public class JarFileSystem extends ZipFileSystem
+{
+ private Attributes attributes;
+
+ protected JarFileSystem(final AbstractFileName rootName,
+ final FileObject file,
+ final FileSystemOptions fileSystemOptions) throws FileSystemException
+ {
+ super(rootName, file, fileSystemOptions);
+ }
+
+// @Override
+// protected FileObject createFile(AbstractFileName name) throws FileSystemException
+// {
+// return new JarFileObject(name, null, this, false);
+// }
+
+ @Override
+ protected ZipFile createZipFile(final File file) throws FileSystemException
+ {
+ try
+ {
+ return new JarFile(file);
+ }
+ catch (final IOException ioe)
+ {
+ throw new FileSystemException("vfs.provider.jar/open-jar-file.error", file, ioe);
+ }
+ }
+
+ @Override
+ protected ZipFileObject createZipFileObject(final AbstractFileName name,
+ final ZipEntry entry) throws FileSystemException
+ {
+ return new JarFileObject(name, entry, this, true);
+ }
+
+ /**
+ * Returns the capabilities of this file system.
+ */
+ @Override
+ protected void addCapabilities(final Collection<Capability> caps)
+ {
+ // super.addCapabilities(caps);
+ caps.addAll(JarFileProvider.capabilities);
+ }
+
+ Attributes getAttributes() throws IOException
+ {
+ if (attributes == null)
+ {
+ final Manifest man = ((JarFile) getZipFile()).getManifest();
+ if (man == null)
+ {
+ attributes = new Attributes(1);
+ }
+ else
+ {
+ attributes = man.getMainAttributes();
+ if (attributes == null)
+ {
+ attributes = new Attributes(1);
+ }
+ }
+ }
+
+ return attributes;
+ }
+
+ Object getAttribute(final Name attrName)
+ throws FileSystemException
+ {
+ try
+ {
+ final Attributes attr = getAttributes();
+ final String value = attr.getValue(attrName);
+ return value;
+ }
+ catch (final IOException ioe)
+ {
+ throw new FileSystemException(attrName.toString(), ioe);
+ }
+ }
+
+ Name lookupName(final String attrName)
+ {
+ if (Name.CLASS_PATH.toString().equals(attrName))
+ {
+ return Name.CLASS_PATH;
+ }
+ else if (Name.CONTENT_TYPE.toString().equals(attrName))
+ {
+ return Name.CONTENT_TYPE;
+ }
+ else if (Name.EXTENSION_INSTALLATION.toString().equals(attrName))
+ {
+ return Name.EXTENSION_INSTALLATION;
+ }
+ else if (Name.EXTENSION_LIST.toString().equals(attrName))
+ {
+ return Name.EXTENSION_LIST;
+ }
+ else if (Name.EXTENSION_NAME.toString().equals(attrName))
+ {
+ return Name.EXTENSION_NAME;
+ }
+ else if (Name.IMPLEMENTATION_TITLE.toString().equals(attrName))
+ {
+ return Name.IMPLEMENTATION_TITLE;
+ }
+ else if (Name.IMPLEMENTATION_URL.toString().equals(attrName))
+ {
+ return Name.IMPLEMENTATION_URL;
+ }
+ else if (Name.IMPLEMENTATION_VENDOR.toString().equals(attrName))
+ {
+ return Name.IMPLEMENTATION_VENDOR;
+ }
+ else if (Name.IMPLEMENTATION_VENDOR_ID.toString().equals(attrName))
+ {
+ return Name.IMPLEMENTATION_VENDOR_ID;
+ }
+ else if (Name.IMPLEMENTATION_VERSION.toString().equals(attrName))
+ {
+ return Name.IMPLEMENTATION_VENDOR;
+ }
+ else if (Name.MAIN_CLASS.toString().equals(attrName))
+ {
+ return Name.MAIN_CLASS;
+ }
+ else if (Name.MANIFEST_VERSION.toString().equals(attrName))
+ {
+ return Name.MANIFEST_VERSION;
+ }
+ else if (Name.SEALED.toString().equals(attrName))
+ {
+ return Name.SEALED;
+ }
+ else if (Name.SIGNATURE_VERSION.toString().equals(attrName))
+ {
+ return Name.SIGNATURE_VERSION;
+ }
+ else if (Name.SPECIFICATION_TITLE.toString().equals(attrName))
+ {
+ return Name.SPECIFICATION_TITLE;
+ }
+ else if (Name.SPECIFICATION_VENDOR.toString().equals(attrName))
+ {
+ return Name.SPECIFICATION_VENDOR;
+ }
+ else if (Name.SPECIFICATION_VERSION.toString().equals(attrName))
+ {
+ return Name.SPECIFICATION_VERSION;
+ }
+ else
+ {
+ return new Name(attrName);
+ }
+ }
+
+ /**
+ * Retrives the attribute with the specified name. The default
+ * implementation simply throws an exception.
+ * @param attrName The attiribute's name.
+ * @return The value of the attribute.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public Object getAttribute(final String attrName) throws FileSystemException
+ {
+ final Name name = lookupName(attrName);
+ return getAttribute(name);
+ }
+
+
+ @Override
+ protected ZipFile getZipFile() throws FileSystemException
+ {
+ // make accessible
+ return super.getZipFile();
+ }
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/jar/JarURLConnectionImpl.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/jar/JarURLConnectionImpl.java
new file mode 100644
index 0000000..119b426
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/jar/JarURLConnectionImpl.java
@@ -0,0 +1,144 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.jar;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.JarURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.security.cert.Certificate;
+import java.util.jar.Attributes;
+import java.util.jar.JarEntry;
+import java.util.jar.JarFile;
+import java.util.jar.Manifest;
+
+import org.apache.commons.vfs2.FileContent;
+import org.apache.commons.vfs2.FileSystemException;
+
+/**
+ * A default URL connection that will work for most file systems.
+ */
+public class JarURLConnectionImpl
+ extends JarURLConnection
+{
+ // This is because JarURLConnection SUCKS
+ private static final String HACK_URL = "jar:http://somehost/somejar.jar!/";
+
+ private final FileContent content;
+ private final URL parentURL;
+ private final JarFileObject file;
+ private final String entryName;
+
+ public JarURLConnectionImpl(final JarFileObject file, final FileContent content)
+ throws MalformedURLException, FileSystemException
+ {
+ //This is because JarURLConnection SUCKS!!
+ super(new URL(HACK_URL));
+
+ this.url = file.getURL();
+ this.content = content;
+ this.parentURL = file.getURL();
+ this.entryName = file.getName().getPath();
+ this.file = file;
+ }
+
+
+ @Override
+ public URL getJarFileURL()
+ {
+ return parentURL;
+ }
+
+
+ @Override
+ public String getEntryName()
+ {
+ return entryName;
+ }
+
+
+ @Override
+ public JarFile getJarFile() throws IOException
+ {
+ throw new FileSystemException("vfs.provider.jar/jar-file-no-access.error");
+ }
+
+
+ @Override
+ public Manifest getManifest() throws IOException
+ {
+ return file.getManifest();
+ }
+
+
+ @Override
+ public JarEntry getJarEntry() throws IOException
+ {
+ throw new FileSystemException("vfs.provider.jar/jar-entry-no-access.error");
+ }
+
+
+ @Override
+ public Attributes getAttributes() throws IOException
+ {
+ return file.getAttributes();
+ }
+
+
+ @Override
+ public Certificate[] getCertificates()
+ {
+ return file.doGetCertificates();
+ }
+
+
+ @Override
+ public void connect()
+ {
+ connected = true;
+ }
+
+ @Override
+ public InputStream getInputStream()
+ throws IOException
+ {
+ return content.getInputStream();
+ }
+
+ @Override
+ public OutputStream getOutputStream()
+ throws IOException
+ {
+ return content.getOutputStream();
+ }
+
+ @Override
+ public int getContentLength()
+ {
+ try
+ {
+ return (int) content.getSize();
+ }
+ catch (final FileSystemException ignored)
+ {
+ return -1;
+ }
+ }
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/jar/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/jar/package.html
new file mode 100644
index 0000000..8383735
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/jar/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>The Jar File Provider.</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/DefaultLocalFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/DefaultLocalFileProvider.java
new file mode 100644
index 0000000..dae0f5c
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/DefaultLocalFileProvider.java
@@ -0,0 +1,140 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.local;
+
+import java.io.File;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider;
+import org.apache.commons.vfs2.provider.LocalFileProvider;
+import org.apache.commons.vfs2.provider.UriParser;
+import org.apache.commons.vfs2.util.Os;
+
+/**
+ * A file system provider, which uses direct file access.
+ */
+public class DefaultLocalFileProvider
+ extends AbstractOriginatingFileProvider
+ implements LocalFileProvider
+{
+ /** The provider's capabilities. */
+ public static final Collection<Capability> capabilities =
+ Collections.unmodifiableCollection(Arrays.asList(new Capability[]
+ {
+ Capability.CREATE,
+ Capability.DELETE,
+ Capability.RENAME,
+ Capability.GET_TYPE,
+ Capability.GET_LAST_MODIFIED,
+ Capability.SET_LAST_MODIFIED_FILE,
+ Capability.SET_LAST_MODIFIED_FOLDER,
+ Capability.LIST_CHILDREN,
+ Capability.READ_CONTENT,
+ Capability.URI,
+ Capability.WRITE_CONTENT,
+ Capability.APPEND_CONTENT,
+ Capability.RANDOM_ACCESS_READ,
+ Capability.RANDOM_ACCESS_SET_LENGTH,
+ Capability.RANDOM_ACCESS_WRITE
+ }));
+
+ /**
+ * Constructs a new provider.
+ */
+ public DefaultLocalFileProvider()
+ {
+ super();
+
+ if (Os.isFamily(Os.OS_FAMILY_WINDOWS))
+ {
+ setFileNameParser(new WindowsFileNameParser());
+ }
+ else
+ {
+ setFileNameParser(new GenericFileNameParser());
+ }
+ }
+
+ /**
+ * Determines if a name is an absolute file name.
+ * @param name The file name.
+ * @return true if the name is absolute, false otherwise.
+ */
+ @Override
+ public boolean isAbsoluteLocalName(final String name)
+ {
+ return ((LocalFileNameParser) getFileNameParser()).isAbsoluteName(name);
+ }
+
+ /**
+ * Finds a local file, from its local name.
+ * @param name The name of the file to locate.
+ * @return the located FileObject.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileObject findLocalFile(final String name)
+ throws FileSystemException
+ {
+ final String scheme = "file:";
+ final StringBuilder uri = new StringBuilder(name.length() + scheme.length());
+ uri.append(scheme);
+ uri.append(name);
+ final FileName filename = parseUri(null, uri.toString());
+ return findFile(filename, null);
+ }
+
+ /**
+ * Finds a local file.
+ * @param file The File to locate.
+ * @return the located FileObject.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileObject findLocalFile(final File file)
+ throws FileSystemException
+ {
+ return findLocalFile(UriParser.encode(file.getAbsolutePath()));
+ // return findLocalFile(file.getAbsolutePath());
+ }
+
+ /**
+ * Creates the filesystem.
+ */
+ @Override
+ protected FileSystem doCreateFileSystem(final FileName name, final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ // Create the file system
+ final LocalFileName rootName = (LocalFileName) name;
+ return new LocalFileSystem(rootName, rootName.getRootFile(), fileSystemOptions);
+ }
+
+ @Override
+ public Collection<Capability> getCapabilities()
+ {
+ return capabilities;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/GenericFileNameParser.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/GenericFileNameParser.java
new file mode 100644
index 0000000..f75a828
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/GenericFileNameParser.java
@@ -0,0 +1,72 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.local;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+
+/**
+ * A general-purpose file name parser.
+ */
+public class GenericFileNameParser
+ extends LocalFileNameParser
+{
+ private static final GenericFileNameParser INSTANCE = new GenericFileNameParser();
+
+ /**
+ * retrieve a instance to this parser.
+ *
+ * @return the parser
+ */
+ public static GenericFileNameParser getInstance()
+ {
+ return INSTANCE;
+ }
+
+ /**
+ * Pops the root prefix off a URI, which has had the scheme removed.
+ */
+ @Override
+ protected String extractRootPrefix(final String uri,
+ final StringBuilder name)
+ throws FileSystemException
+ {
+ // TODO - this class isn't generic at all. Need to fix this
+
+ // Looking for <sep>
+ if (name.length() == 0 || name.charAt(0) != '/')
+ {
+ throw new FileSystemException("vfs.provider.local/not-absolute-file-name.error", uri);
+ }
+
+ // do not strip the separator, BUT also return it ...
+ return "/";
+ }
+
+ /*
+ * ... this is why whe need this:
+ * here the rootFilename can only be "/" (see above) put this "/" is also in the pathname
+ * so its of no value for the LocalFileName instance
+ */
+ @Override
+ protected FileName createFileName(final String scheme, final String rootFile,
+ final String path, final FileType type)
+ {
+ return new LocalFileName(scheme, "", path, type);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/LocalFile.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/LocalFile.java
new file mode 100644
index 0000000..8d5beef
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/LocalFile.java
@@ -0,0 +1,311 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.local;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.RandomAccessContent;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileObject;
+import org.apache.commons.vfs2.provider.UriParser;
+import org.apache.commons.vfs2.util.FileObjectUtils;
+import org.apache.commons.vfs2.util.RandomAccessMode;
+
+/**
+ * A file object implementation which uses direct file access.
+ */
+public class LocalFile extends AbstractFileObject<LocalFileSystem>
+{
+ private final String rootFile;
+
+ private File file;
+
+ /**
+ * Creates a non-root file.
+ *
+ * @param fileSystem the file system this file belongs to.
+ * @param rootFile the root file for the file system.
+ * @param name the file name on this file system.
+ * @throws FileSystemException if an error occurs.
+ */
+ protected LocalFile(final LocalFileSystem fileSystem,
+ final String rootFile,
+ final AbstractFileName name) throws FileSystemException
+ {
+ super(name, fileSystem);
+ this.rootFile = rootFile;
+ }
+
+ /**
+ * Returns the local file that this file object represents.
+ *
+ * @return the local file that this file object represents.
+ */
+ protected File getLocalFile()
+ {
+ return file;
+ }
+
+ /**
+ * Attaches this file object to its file resource.
+ */
+ @Override
+ protected void doAttach() throws Exception
+ {
+ if (file == null)
+ {
+ // Remove the "file:///"
+ // LocalFileName localFileName = (LocalFileName) getName();
+ final String fileName = rootFile + getName().getPathDecoded();
+ // fileName = UriParser.decode(fileName);
+ file = new File(fileName);
+ }
+ }
+
+ /**
+ * Returns the file's type.
+ */
+ @Override
+ protected FileType doGetType() throws Exception
+ {
+ // JDK BUG: 6192331
+ // if (!file.exists())
+ if (!file.exists() && file.length() < 1)
+ {
+ return FileType.IMAGINARY;
+ }
+
+ if (file.isDirectory())
+ {
+ return FileType.FOLDER;
+ }
+
+ // In doubt, treat an existing file as file
+ // if (file.isFile())
+ // {
+ return FileType.FILE;
+ // }
+
+ // throw new FileSystemException("vfs.provider.local/get-type.error", file);
+ }
+
+ /**
+ * Returns the children of the file.
+ */
+ @Override
+ protected String[] doListChildren() throws Exception
+ {
+ return UriParser.encode(file.list());
+ }
+
+ /**
+ * Deletes this file, and all children.
+ */
+ @Override
+ protected void doDelete() throws Exception
+ {
+ if (!file.delete())
+ {
+ throw new FileSystemException("vfs.provider.local/delete-file.error", file);
+ }
+ }
+
+ /**
+ * rename this file
+ */
+ @Override
+ protected void doRename(final FileObject newFile) throws Exception
+ {
+ final LocalFile newLocalFile = (LocalFile) FileObjectUtils.getAbstractFileObject(newFile);
+
+ if (!file.renameTo(newLocalFile.getLocalFile()))
+ {
+ throw new FileSystemException("vfs.provider.local/rename-file.error",
+ file.toString(), newFile.toString());
+ }
+ }
+
+ /**
+ * Creates this folder.
+ */
+ @Override
+ protected void doCreateFolder() throws Exception
+ {
+ if (!file.mkdirs())
+ {
+ throw new FileSystemException("vfs.provider.local/create-folder.error", file);
+ }
+ }
+
+ /**
+ * Determines if this file can be written to.
+ */
+ @Override
+ protected boolean doIsWriteable() throws FileSystemException
+ {
+ return file.canWrite();
+ }
+
+ @Override
+ protected boolean doSetWritable(final boolean writable, final boolean ownerOnly) throws Exception
+ {
+ return file.setWritable(writable, ownerOnly);
+ }
+
+ /**
+ * Determines if this file is hidden.
+ */
+ @Override
+ protected boolean doIsExecutable()
+ {
+ return file.canExecute();
+ }
+
+ /**
+ * Determines if this file is hidden.
+ */
+ @Override
+ protected boolean doIsHidden()
+ {
+ return file.isHidden();
+ }
+
+ /**
+ * Determines if this file can be read.
+ */
+ @Override
+ protected boolean doIsReadable() throws FileSystemException
+ {
+ return file.canRead();
+ }
+
+ @Override
+ protected boolean doSetReadable(final boolean readable, final boolean ownerOnly) throws Exception
+ {
+ return file.setReadable(readable, ownerOnly);
+ }
+
+ @Override
+ protected boolean doSetExecutable(final boolean executable, final boolean ownerOnly) throws Exception
+ {
+ return file.setExecutable(executable, ownerOnly);
+ }
+
+ /**
+ * Gets the last modified time of this file.
+ */
+ @Override
+ protected long doGetLastModifiedTime() throws FileSystemException
+ {
+ return file.lastModified();
+ }
+
+ /**
+ * Sets the last modified time of this file.
+ * @since 2.0
+ */
+ @Override
+ protected boolean doSetLastModifiedTime(final long modtime) throws FileSystemException
+ {
+ return file.setLastModified(modtime);
+ }
+
+ /**
+ * Creates an input stream to read the content from.
+ */
+ @Override
+ protected InputStream doGetInputStream() throws Exception
+ {
+ return new FileInputStream(file);
+ }
+
+ /**
+ * Creates an output stream to write the file content to.
+ */
+ @Override
+ protected OutputStream doGetOutputStream(final boolean bAppend)
+ throws Exception
+ {
+ return new FileOutputStream(file.getPath(), bAppend);
+ }
+
+ /**
+ * Returns the size of the file content (in bytes).
+ */
+ @Override
+ protected long doGetContentSize() throws Exception
+ {
+ return file.length();
+ }
+
+ @Override
+ protected RandomAccessContent doGetRandomAccessContent(final RandomAccessMode mode) throws Exception
+ {
+ return new LocalFileRandomAccessContent(file, mode);
+ }
+
+ @Override
+ protected boolean doIsSameFile(final FileObject destFile) throws FileSystemException
+ {
+ if (!FileObjectUtils.isInstanceOf(destFile, LocalFile.class))
+ {
+ return false;
+ }
+
+ final LocalFile destLocalFile = (LocalFile) FileObjectUtils.getAbstractFileObject(destFile);
+ if (!exists() || !destLocalFile.exists())
+ {
+ return false;
+ }
+
+ try
+ {
+ return file.getCanonicalPath().equals(destLocalFile.file.getCanonicalPath());
+ }
+ catch (final IOException e)
+ {
+ throw new FileSystemException(e);
+ }
+ }
+
+ /**
+ * Returns the URI of the file.
+ * @return The URI of the file.
+ */
+ @Override
+ public String toString()
+ {
+ try
+ {
+ // VFS-325: URI may contain percent-encoded values as part of filename, so decode
+ // those characters before returning
+ return UriParser.decode(getName().getURI());
+ }
+ catch (final FileSystemException e)
+ {
+ return getName().getURI();
+ }
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/LocalFileName.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/LocalFileName.java
new file mode 100644
index 0000000..74795b5
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/LocalFileName.java
@@ -0,0 +1,162 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.local;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.UriParser;
+
+/**
+ * A local file URI.
+ */
+public class LocalFileName extends AbstractFileName
+{
+ // URI Characters that are possible in local filenames, but must be escaped
+ // for proper URI handling.
+ //
+ // How reserved URI chars were selected:
+ //
+ // URIs can contain :, /, ?, #, @
+ // See http://download.oracle.com/javase/6/docs/api/java/net/URI.html
+ // http://tools.ietf.org/html/rfc3986#section-2.2
+ //
+ // Since : and / occur before the path, only chars after path are escaped (i.e., # and ?)
+ // ? is a reserved filesystem character for Windows and Unix, so can't be part of a filename.
+ // Therefore only # is a reserved char in a URI as part of the path that can be in the filename.
+ private static final char[] RESERVED_URI_CHARS = {'#'};
+
+
+ private final String rootFile;
+
+ protected LocalFileName(final String scheme,
+ final String rootFile,
+ final String path,
+ final FileType type)
+ {
+ super(scheme, path, type);
+ this.rootFile = rootFile;
+ }
+
+ /**
+ * Returns the root file for this file.
+ * @return The root file name.
+ */
+ public String getRootFile()
+ {
+ return rootFile;
+ }
+
+ /**
+ * Factory method for creating name instances.
+ * @param path The file path.
+ * @param type The file type.
+ * @return The FileName.
+ */
+ @Override
+ public FileName createName(final String path, final FileType type)
+ {
+ return new LocalFileName(getScheme(), rootFile, path, type);
+ }
+
+ /**
+ * Returns the absolute URI of the file.
+ * @return The absolute URI of the file.
+ */
+ @Override
+ public String getURI()
+ {
+ String uri = super.getURI();
+
+ if (uri != null && uri.length() > 0)
+ {
+ try
+ {
+ // VFS-325: Handle URI special characters in filename
+ // Decode the base uri and re-encode with URI special characters
+ uri = UriParser.decode(uri);
+
+ uri = UriParser.encode(uri, RESERVED_URI_CHARS);
+ }
+ catch (final FileSystemException e)
+ {
+ // Default to base uri value
+ }
+ }
+
+ return uri;
+ }
+
+ /**
+ * returns a "friendly path", this is a path without a password.
+ * @return The "friendly" URI.
+ */
+ @Override
+ public String getFriendlyURI()
+ {
+ String uri = super.getFriendlyURI();
+
+ if (uri != null && uri.length() > 0)
+ {
+ try
+ {
+ // VFS-325: Handle URI special characters in filename
+ // Decode the base uri and re-encode with URI special characters
+ uri = UriParser.decode(uri);
+
+ uri = UriParser.encode(uri, RESERVED_URI_CHARS);
+ }
+ catch (final FileSystemException e)
+ {
+ // Default to base uri value
+ }
+ }
+
+ return uri;
+ }
+
+ /**
+ * Returns the decoded URI of the file.
+ * @return the FileName as a URI.
+ */
+ @Override
+ public String toString()
+ {
+ try
+ {
+ return UriParser.decode(super.getURI());
+ }
+ catch (final FileSystemException e)
+ {
+ return super.getURI();
+ }
+ }
+
+
+
+ /**
+ * Builds the root URI for this file name.
+ */
+ @Override
+ protected void appendRootUri(final StringBuilder buffer, final boolean addPassword)
+ {
+ buffer.append(getScheme());
+ buffer.append("://");
+ buffer.append(rootFile);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/LocalFileNameParser.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/LocalFileNameParser.java
new file mode 100644
index 0000000..d272f93
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/LocalFileNameParser.java
@@ -0,0 +1,100 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.local;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.provider.AbstractFileNameParser;
+import org.apache.commons.vfs2.provider.UriParser;
+import org.apache.commons.vfs2.provider.VfsComponentContext;
+
+/**
+ * A name parser.
+ */
+public abstract class LocalFileNameParser extends AbstractFileNameParser
+{
+ /**
+ * Determines if a name is an absolute file name.
+ * @param name The file name.
+ * @return true if the name is absolute, false otherwise.
+ */
+ public boolean isAbsoluteName(final String name)
+ {
+ // TODO - this is yucky
+ final StringBuilder b = new StringBuilder(name);
+ try
+ {
+ UriParser.fixSeparators(b);
+ extractRootPrefix(name, b);
+ return true;
+ }
+ catch (final FileSystemException e)
+ {
+ return false;
+ }
+ }
+
+ /**
+ * Pops the root prefix off a URI, which has had the scheme removed.
+ *
+ * @param name the URI to modify.
+ * @param uri the whole URI for error reporting.
+ * @return the root prefix extracted.
+ * @throws FileSystemException if an error occurs.
+ */
+ protected abstract String extractRootPrefix(final String uri,
+ final StringBuilder name)
+ throws FileSystemException;
+
+
+ @Override
+ public FileName parseUri(final VfsComponentContext context, final FileName base, final String uri)
+ throws FileSystemException
+ {
+ final StringBuilder name = new StringBuilder();
+
+ // Extract the scheme
+ String scheme = UriParser.extractScheme(uri, name);
+ if (scheme == null)
+ {
+ scheme = "file";
+ }
+
+ // Remove encoding, and adjust the separators
+ UriParser.canonicalizePath(name, 0, name.length(), this);
+
+ UriParser.fixSeparators(name);
+
+ // Extract the root prefix
+ final String rootFile = extractRootPrefix(uri, name);
+
+ // Normalise the path
+ final FileType fileType = UriParser.normalisePath(name);
+
+ final String path = name.toString();
+
+ return createFileName(
+ scheme,
+ rootFile,
+ path,
+ fileType);
+ }
+
+ protected abstract FileName createFileName(String scheme, final String rootFile, final String path,
+ final FileType type);
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/LocalFileRandomAccessContent.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/LocalFileRandomAccessContent.java
new file mode 100644
index 0000000..ba9d5a1
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/LocalFileRandomAccessContent.java
@@ -0,0 +1,308 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.local;
+
+import java.io.EOFException;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.RandomAccessFile;
+
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.provider.AbstractRandomAccessContent;
+import org.apache.commons.vfs2.util.RandomAccessMode;
+
+/**
+ * Implements {@link org.apache.commons.vfs2.RandomAccessContent RandomAccessContent} for local files.
+ */
+class LocalFileRandomAccessContent extends AbstractRandomAccessContent
+{
+ // private final LocalFile localFile;
+ private final RandomAccessFile raf;
+ private final InputStream rafis;
+
+ LocalFileRandomAccessContent(final File localFile, final RandomAccessMode mode) throws FileSystemException
+ {
+ super(mode);
+
+ try
+ {
+ raf = new RandomAccessFile(localFile, mode.getModeString());
+ rafis = new InputStream()
+ {
+ @Override
+ public int read() throws IOException
+ {
+ try
+ {
+ return raf.readByte();
+ }
+ catch (final EOFException e)
+ {
+ return -1;
+ }
+ }
+
+ @Override
+ public long skip(final long n) throws IOException
+ {
+ raf.seek(raf.getFilePointer() + n);
+ return n;
+ }
+
+ @Override
+ public void close() throws IOException
+ {
+ raf.close();
+ }
+
+ @Override
+ public int read(final byte[] b) throws IOException
+ {
+ return raf.read(b);
+ }
+
+ @Override
+ public int read(final byte[] b, final int off, final int len) throws IOException
+ {
+ return raf.read(b, off, len);
+ }
+
+ @Override
+ public int available() throws IOException
+ {
+ final long available = raf.length() - raf.getFilePointer();
+ if (available > Integer.MAX_VALUE)
+ {
+ return Integer.MAX_VALUE;
+ }
+
+ return (int) available;
+ }
+ };
+ }
+ catch (final FileNotFoundException e)
+ {
+ throw new FileSystemException("vfs.provider/random-access-open-failed.error", localFile);
+ }
+ }
+
+ @Override
+ public long getFilePointer() throws IOException
+ {
+ return raf.getFilePointer();
+ }
+
+ @Override
+ public void seek(final long pos) throws IOException
+ {
+ raf.seek(pos);
+ }
+
+ @Override
+ public long length() throws IOException
+ {
+ return raf.length();
+ }
+
+ @Override
+ public void close() throws IOException
+ {
+ raf.close();
+ }
+
+ @Override
+ public byte readByte() throws IOException
+ {
+ return raf.readByte();
+ }
+
+ @Override
+ public char readChar() throws IOException
+ {
+ return raf.readChar();
+ }
+
+ @Override
+ public double readDouble() throws IOException
+ {
+ return raf.readDouble();
+ }
+
+ @Override
+ public float readFloat() throws IOException
+ {
+ return raf.readFloat();
+ }
+
+ @Override
+ public int readInt() throws IOException
+ {
+ return raf.readInt();
+ }
+
+ @Override
+ public int readUnsignedByte() throws IOException
+ {
+ return raf.readUnsignedByte();
+ }
+
+ @Override
+ public int readUnsignedShort() throws IOException
+ {
+ return raf.readUnsignedShort();
+ }
+
+ @Override
+ public long readLong() throws IOException
+ {
+ return raf.readLong();
+ }
+
+ @Override
+ public short readShort() throws IOException
+ {
+ return raf.readShort();
+ }
+
+ @Override
+ public boolean readBoolean() throws IOException
+ {
+ return raf.readBoolean();
+ }
+
+ @Override
+ public int skipBytes(final int n) throws IOException
+ {
+ return raf.skipBytes(n);
+ }
+
+ @Override
+ public void readFully(final byte[] b) throws IOException
+ {
+ raf.readFully(b);
+ }
+
+ @Override
+ public void readFully(final byte[] b, final int off, final int len) throws IOException
+ {
+ raf.readFully(b, off, len);
+ }
+
+ @Override
+ public String readUTF() throws IOException
+ {
+ return raf.readUTF();
+ }
+
+ @Override
+ public void writeDouble(final double v) throws IOException
+ {
+ raf.writeDouble(v);
+ }
+
+ @Override
+ public void writeFloat(final float v) throws IOException
+ {
+ raf.writeFloat(v);
+ }
+
+ @Override
+ public void write(final int b) throws IOException
+ {
+ raf.write(b);
+ }
+
+ @Override
+ public void writeByte(final int v) throws IOException
+ {
+ raf.writeByte(v);
+ }
+
+ @Override
+ public void writeChar(final int v) throws IOException
+ {
+ raf.writeChar(v);
+ }
+
+ @Override
+ public void writeInt(final int v) throws IOException
+ {
+ raf.writeInt(v);
+ }
+
+ @Override
+ public void writeShort(final int v) throws IOException
+ {
+ raf.writeShort(v);
+ }
+
+ @Override
+ public void writeLong(final long v) throws IOException
+ {
+ raf.writeLong(v);
+ }
+
+ @Override
+ public void writeBoolean(final boolean v) throws IOException
+ {
+ raf.writeBoolean(v);
+ }
+
+ @Override
+ public void write(final byte[] b) throws IOException
+ {
+ raf.write(b);
+ }
+
+ @Override
+ public void write(final byte[] b, final int off, final int len) throws IOException
+ {
+ raf.write(b, off, len);
+ }
+
+ @Override
+ public void writeBytes(final String s) throws IOException
+ {
+ raf.writeBytes(s);
+ }
+
+ @Override
+ public void writeChars(final String s) throws IOException
+ {
+ raf.writeChars(s);
+ }
+
+ @Override
+ public void writeUTF(final String str) throws IOException
+ {
+ raf.writeUTF(str);
+ }
+
+ @Override
+ public InputStream getInputStream() throws IOException
+ {
+ return rafis;
+ }
+
+ @Override
+ public void setLength(final long newLength) throws IOException
+ {
+ raf.setLength(newLength);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/LocalFileSystem.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/LocalFileSystem.java
new file mode 100644
index 0000000..97b700b
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/LocalFileSystem.java
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.local;
+
+import java.io.File;
+import java.io.FilePermission;
+import java.util.Collection;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSelector;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileSystem;
+import org.apache.commons.vfs2.util.FileObjectUtils;
+
+/**
+ * A local file system.
+ */
+public class LocalFileSystem
+ extends AbstractFileSystem
+{
+ private final String rootFile;
+
+ public LocalFileSystem(final FileName rootName,
+ final String rootFile,
+ final FileSystemOptions opts)
+ {
+ super(rootName, null, opts);
+ this.rootFile = rootFile;
+ }
+
+ /**
+ * Creates a file object.
+ */
+ @Override
+ protected FileObject createFile(final AbstractFileName name) throws FileSystemException
+ {
+ // Create the file
+ return new LocalFile(this, rootFile, name);
+ }
+
+ /**
+ * Returns the capabilities of this file system.
+ */
+ @Override
+ protected void addCapabilities(final Collection<Capability> caps)
+ {
+ caps.addAll(DefaultLocalFileProvider.capabilities);
+ }
+
+ /**
+ * Creates a temporary local copy of a file and its descendants.
+ */
+ @Override
+ protected File doReplicateFile(final FileObject fileObject,
+ final FileSelector selector)
+ throws Exception
+ {
+ final LocalFile localFile = (LocalFile) FileObjectUtils.getAbstractFileObject(fileObject);
+ final File file = localFile.getLocalFile();
+ final SecurityManager sm = System.getSecurityManager();
+ if (sm != null)
+ {
+ final FilePermission requiredPerm = new FilePermission(file.getAbsolutePath(), "read");
+ sm.checkPermission(requiredPerm);
+ }
+ return file;
+ }
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/WindowsFileName.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/WindowsFileName.java
new file mode 100644
index 0000000..9b387b7
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/WindowsFileName.java
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.local;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileType;
+
+/**
+ * A local file URI.
+ */
+public class WindowsFileName extends LocalFileName
+{
+ protected WindowsFileName(final String scheme,
+ final String rootFile,
+ final String path,
+ final FileType type)
+ {
+ super(scheme, rootFile, path, type);
+ }
+
+ /**
+ * Factory method for creating name instances.
+ * @param path The file path.
+ * @param type The file type.
+ * @return The FileName.
+ */
+ @Override
+ public FileName createName(final String path, final FileType type)
+ {
+ return new WindowsFileName(getScheme(), getRootFile(), path, type);
+ }
+
+ /**
+ * Builds the root URI for this file name.
+ */
+ @Override
+ protected void appendRootUri(final StringBuilder buffer, final boolean addPassword)
+ {
+ buffer.append(getScheme());
+ buffer.append("://");
+ if (getRootFile() != null && !getRootFile().startsWith("/"))
+ {
+ // next is drive-letter (else unc name)
+ buffer.append("/");
+ }
+ buffer.append(getRootFile());
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/WindowsFileNameParser.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/WindowsFileNameParser.java
new file mode 100644
index 0000000..cd5f4e5
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/WindowsFileNameParser.java
@@ -0,0 +1,156 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.local;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+
+/**
+ * A parser for Windows file names.
+ */
+public class WindowsFileNameParser extends LocalFileNameParser
+{
+ /**
+ * Pops the root prefix off a URI, which has had the scheme removed.
+ */
+ @Override
+ protected String extractRootPrefix(final String uri,
+ final StringBuilder name)
+ throws FileSystemException
+ {
+ return extractWindowsRootPrefix(uri, name);
+ }
+
+ @Override
+ protected FileName createFileName(final String scheme, final String rootFile,
+ final String path, final FileType type)
+ {
+ return new WindowsFileName(scheme, rootFile, path, type);
+ }
+
+ /**
+ * Extracts a Windows root prefix from a name.
+ */
+ private String extractWindowsRootPrefix(final String uri,
+ final StringBuilder name)
+ throws FileSystemException
+ {
+ // Looking for:
+ // ('/'){0, 3} <letter> ':' '/'
+ // ['/'] '//' <name> '/' <name> ( '/' | <end> )
+
+ // Skip over first 4 (unc) leading '/' chars
+ int startPos = 0;
+ final int maxlen = Math.min(4, name.length());
+ for (; startPos < maxlen && name.charAt(startPos) == '/'; startPos++)
+ {
+ }
+ if (startPos == maxlen && name.length() > (startPos + 1) && name.charAt(startPos + 1) == '/')
+ {
+ // Too many '/'
+ throw new FileSystemException("vfs.provider.local/not-absolute-file-name.error", uri);
+ }
+ name.delete(0, startPos);
+
+ // Look for drive name
+ final String driveName = extractDrivePrefix(name);
+ if (driveName != null)
+ {
+ return driveName;
+ }
+
+ // Look for UNC name
+ if (startPos < 2)
+ {
+ throw new FileSystemException("vfs.provider.local/not-absolute-file-name.error", uri);
+ }
+
+ return "//" + extractUNCPrefix(uri, name);
+ }
+
+ /**
+ * Extracts a drive prefix from a path. Leading '/' chars have been removed.
+ */
+ private String extractDrivePrefix(final StringBuilder name)
+ {
+ // Looking for <letter> ':' '/'
+ if (name.length() < 3)
+ {
+ // Too short
+ return null;
+ }
+ final char ch = name.charAt(0);
+ if (ch == '/' || ch == ':')
+ {
+ // Missing drive letter
+ return null;
+ }
+ if (name.charAt(1) != ':')
+ {
+ // Missing ':'
+ return null;
+ }
+ if (name.charAt(2) != '/')
+ {
+ // Missing separator
+ return null;
+ }
+
+ final String prefix = name.substring(0, 2);
+ name.delete(0, 2);
+
+ return prefix.intern();
+ }
+
+ /**
+ * Extracts a UNC name from a path. Leading '/' chars have been removed.
+ */
+ private String extractUNCPrefix(final String uri,
+ final StringBuilder name)
+ throws FileSystemException
+ {
+ // Looking for <name> '/' <name> ( '/' | <end> )
+
+ // Look for first separator
+ final int maxpos = name.length();
+ int pos = 0;
+ for (; pos < maxpos && name.charAt(pos) != '/'; pos++)
+ {
+ }
+ pos++;
+ if (pos >= maxpos)
+ {
+ throw new FileSystemException("vfs.provider.local/missing-share-name.error", uri);
+ }
+
+ // Now have <name> '/'
+ final int startShareName = pos;
+ for (; pos < maxpos && name.charAt(pos) != '/'; pos++)
+ {
+ }
+ if (pos == startShareName)
+ {
+ throw new FileSystemException("vfs.provider.local/missing-share-name.error", uri);
+ }
+
+ // Now have <name> '/' <name> ( '/' | <end> )
+ final String prefix = name.substring(0, pos);
+ name.delete(0, pos);
+ return prefix;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/package.html
new file mode 100644
index 0000000..2936b87
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/local/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>The Local File Provider.</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/package.html
new file mode 100644
index 0000000..27fac1e
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>The File Provider API, and utility classes.</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileData.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileData.java
new file mode 100644
index 0000000..d27a34e
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileData.java
@@ -0,0 +1,293 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ram;
+
+import java.io.Serializable;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+
+/**
+ * RAM File Object Data.
+ */
+class RamFileData implements Serializable
+{
+ static final byte[] EMPTY = new byte[0];
+
+ /**
+ * serialVersionUID format is YYYYMMDD for the date of the last binary change.
+ */
+ private static final long serialVersionUID = 20101208L;
+
+ /**
+ * File Name.
+ */
+ private FileName name;
+
+ /**
+ * File Type.
+ */
+ private FileType type;
+
+ /**
+ * Bytes.
+ */
+ private byte[] content;
+
+ /**
+ * Last modified time
+ */
+ private long lastModified;
+
+ /**
+ * Children
+ */
+ private final Collection<RamFileData> children;
+
+ /**
+ * Constructor.
+ * @param name The file name.
+ */
+ public RamFileData(final FileName name)
+ {
+ super();
+ this.children = Collections.synchronizedCollection(new ArrayList<RamFileData>());
+ this.clear();
+ if (name == null)
+ {
+ throw new IllegalArgumentException("name can not be null");
+ }
+ this.name = name;
+ }
+
+ /**
+ * @return Returns the buffer.
+ */
+ byte[] getContent()
+ {
+ return content;
+ }
+
+ /**
+ * @param content The buffer.
+ */
+ void setContent(final byte[] content)
+ {
+ updateLastModified();
+ this.content = content;
+ }
+
+ /**
+ * @return Returns the lastModified.
+ */
+ long getLastModified()
+ {
+ return lastModified;
+ }
+
+ /**
+ * @param lastModified
+ * The lastModified to set.
+ */
+ void setLastModified(final long lastModified)
+ {
+ this.lastModified = lastModified;
+ }
+
+ /**
+ * @return Returns the type.
+ */
+ FileType getType()
+ {
+ return type;
+ }
+
+ /**
+ * @param type
+ * The type to set.
+ */
+ void setType(final FileType type)
+ {
+ this.type = type;
+ }
+
+ /**
+ */
+ void clear()
+ {
+ this.content = EMPTY;
+ updateLastModified();
+ this.type = FileType.IMAGINARY;
+ this.children.clear();
+ this.name = null;
+ }
+
+ void updateLastModified()
+ {
+ this.lastModified = System.currentTimeMillis();
+ }
+
+ /**
+ * @return Returns the name.
+ */
+ FileName getName()
+ {
+ return name;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#toString()
+ */
+ @Override
+ public String toString()
+ {
+ return this.name.toString();
+ }
+
+ /**
+ * Add a child.
+ *
+ * @param data The file data.
+ * @throws FileSystemException if an error occurs.
+ */
+ void addChild(final RamFileData data) throws FileSystemException
+ {
+ if (!this.getType().hasChildren())
+ {
+ throw new FileSystemException(
+ "A child can only be added in a folder");
+ }
+
+ if (data == null)
+ {
+ throw new FileSystemException("No child can be null");
+ }
+
+ if (this.children.contains(data))
+ {
+ throw new FileSystemException("Child already exists. " + data);
+ }
+
+ this.children.add(data);
+ updateLastModified();
+ }
+
+ /**
+ * Remove a child.
+ *
+ * @param data The file data.
+ * @throws FileSystemException if an error occurs.
+ */
+ void removeChild(final RamFileData data) throws FileSystemException
+ {
+ if (!this.getType().hasChildren())
+ {
+ throw new FileSystemException(
+ "A child can only be removed from a folder");
+ }
+ if (!this.children.contains(data))
+ {
+ throw new FileSystemException("Child not found. " + data);
+ }
+ this.children.remove(data);
+ updateLastModified();
+ }
+
+ /**
+ * @return Returns the children.
+ */
+ Collection<RamFileData> getChildren()
+ {
+ if (name == null)
+ {
+ throw new IllegalStateException("Data is clear");
+ }
+ return children;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#equals(java.lang.Object)
+ */
+ @Override
+ public boolean equals(final Object o)
+ {
+ if (this == o)
+ {
+ return true;
+ }
+ if (!(o instanceof RamFileData))
+ {
+ return false;
+ }
+ final RamFileData data = (RamFileData) o;
+ return this.getName().equals(data.getName());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.lang.Object#hashCode()
+ */
+ @Override
+ public int hashCode()
+ {
+ return this.getName().hashCode();
+ }
+
+ boolean hasChildren(final RamFileData data)
+ {
+ return this.children.contains(data);
+ }
+
+ /**
+ * @return Returns the size of the buffer
+ */
+ int size()
+ {
+ return content.length;
+ }
+
+ /**
+ * Resize the buffer
+ *
+ * @param newSize The new buffer size.
+ */
+ void resize(final long newSize)
+ {
+ // A future implementation may allow longs/multiple buffer/and so on
+ if (newSize > Integer.MAX_VALUE)
+ {
+ throw new IllegalArgumentException(String.format("newSize(%d) > Integer.MAX_VALUE(%d)", newSize,
+ Integer.MAX_VALUE));
+ }
+ final int resize = (int) newSize;
+ final int size = this.size();
+ final byte[] newBuf = new byte[resize];
+ System.arraycopy(this.content, 0, newBuf, 0, Math.min(resize, size));
+ this.content = newBuf;
+ updateLastModified();
+ }
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileObject.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileObject.java
new file mode 100644
index 0000000..b0bad27
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileObject.java
@@ -0,0 +1,283 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ram;
+
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.RandomAccessContent;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileObject;
+import org.apache.commons.vfs2.util.FileObjectUtils;
+import org.apache.commons.vfs2.util.RandomAccessMode;
+
+/**
+ * A RAM File contains a single RAM FileData instance, it provides methods to access the data by implementing FileObject
+ * interface.
+ */
+public class RamFileObject extends AbstractFileObject<RamFileSystem>
+{
+ /**
+ * RAM File Object Data.
+ */
+ private RamFileData data;
+
+ /**
+ * @param name
+ * The name of the file.
+ * @param fs
+ * The FileSystem.
+ */
+ protected RamFileObject(final AbstractFileName name, final RamFileSystem fs)
+ {
+ super(name, fs);
+ this.getAbstractFileSystem().attach(this);
+ }
+
+ private void save() throws FileSystemException
+ {
+ this.getAbstractFileSystem().save(this);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doGetType()
+ */
+ @Override
+ protected FileType doGetType() throws Exception
+ {
+ return data.getType();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doListChildren()
+ */
+ @Override
+ protected String[] doListChildren() throws Exception
+ {
+ return this.getAbstractFileSystem().listChildren(this.getName());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doGetContentSize()
+ */
+ @Override
+ protected long doGetContentSize() throws Exception
+ {
+ return this.size();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doGetInputStream()
+ */
+ @Override
+ protected InputStream doGetInputStream() throws Exception
+ {
+ // VFS-210: ram allows to gather an input stream even from a directory. So we need to check the type anyway.
+ if (!getType().hasContent())
+ {
+ throw new FileSystemException("vfs.provider/read-not-file.error", getName());
+ }
+
+ return new ByteArrayInputStream(this.data.getContent());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doGetOutputStream(boolean)
+ */
+ @Override
+ protected OutputStream doGetOutputStream(final boolean bAppend) throws Exception
+ {
+ if (!bAppend)
+ {
+ this.data.setContent(RamFileData.EMPTY);
+ }
+ return new RamFileOutputStream(this);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doDelete()
+ */
+ @Override
+ protected void doDelete() throws Exception
+ {
+
+ if (this.isContentOpen())
+ {
+ throw new FileSystemException(this.getName() + " cannot be deleted while the file is openg");
+ }
+ getAbstractFileSystem().delete(this);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doGetLastModifiedTime()
+ */
+ @Override
+ protected long doGetLastModifiedTime() throws Exception
+ {
+ return data.getLastModified();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doSetLastModifiedTime(long)
+ */
+ /** @since 2.0 */
+ @Override
+ protected boolean doSetLastModifiedTime(final long modtime) throws Exception
+ {
+ data.setLastModified(modtime);
+ return true;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doCreateFolder()
+ */
+ @Override
+ protected void doCreateFolder() throws Exception
+ {
+ this.injectType(FileType.FOLDER);
+ this.save();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doRename(org.apache.commons.vfs2.FileObject)
+ */
+ @Override
+ protected void doRename(final FileObject newFile) throws Exception
+ {
+ final RamFileObject newRamFileObject = (RamFileObject) FileObjectUtils.getAbstractFileObject(newFile);
+ getAbstractFileSystem().rename(this, newRamFileObject);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doGetRandomAccessContent(
+ * org.apache.commons.vfs2.util.RandomAccessMode)
+ */
+ @Override
+ protected RandomAccessContent doGetRandomAccessContent(final RandomAccessMode mode) throws Exception
+ {
+ return new RamFileRandomAccessContent(this, mode);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#doAttach()
+ */
+ @Override
+ protected void doAttach() throws Exception
+ {
+ this.getAbstractFileSystem().attach(this);
+ }
+
+ /**
+ * @return Returns the data.
+ */
+ RamFileData getData()
+ {
+ return data;
+ }
+
+ /**
+ * @param data
+ * The data to set.
+ */
+ void setData(final RamFileData data)
+ {
+ this.data = data;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#injectType(org.apache.commons.vfs2.FileType)
+ */
+ @Override
+ protected void injectType(final FileType fileType)
+ {
+ this.data.setType(fileType);
+ super.injectType(fileType);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.commons.vfs2.provider.AbstractFileObject#endOutput()
+ */
+ @Override
+ protected void endOutput() throws Exception
+ {
+ super.endOutput();
+ this.save();
+ }
+
+ /**
+ * @return Returns the size of the {@link RamFileData}.
+ */
+ int size()
+ {
+ return data == null ? 0 : data.size();
+ }
+
+ /**
+ * @param newSize
+ * @throws IOException
+ * if the new size exceeds the limit
+ */
+ synchronized void resize(final long newSize) throws IOException
+ {
+ final RamFileSystem afs = getAbstractFileSystem();
+ final FileSystemOptions afsOptions = afs.getFileSystemOptions();
+ if (afsOptions != null)
+ {
+ final long maxSize = RamFileSystemConfigBuilder.getInstance().getLongMaxSize(afsOptions);
+ if (afs.size() + newSize - this.size() > maxSize)
+ {
+ throw new IOException("FileSystem capacity (" + maxSize + ") exceeded.");
+ }
+ }
+ this.data.resize(newSize);
+ }
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileOutputStream.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileOutputStream.java
new file mode 100644
index 0000000..ed62961
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileOutputStream.java
@@ -0,0 +1,119 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ram;
+
+import java.io.IOException;
+import java.io.OutputStream;
+
+import org.apache.commons.vfs2.FileSystemException;
+
+/**
+ * OutputStream to a RamFile.
+ */
+public class RamFileOutputStream extends OutputStream
+{
+
+ /**
+ * File.
+ */
+ protected RamFileObject file;
+
+ /**
+ * buffer.
+ */
+ protected byte[] buffer1 = new byte[1];
+
+ /** File is open or closed */
+ protected boolean closed = false;
+
+ private IOException exception;
+
+ /**
+ * @param file The base file.
+ */
+ public RamFileOutputStream(final RamFileObject file)
+ {
+ super();
+ this.file = file;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataOutput#write(byte[], int, int)
+ */
+ @Override
+ public void write(final byte[] b, final int off, final int len) throws IOException
+ {
+ final RamFileData data = this.file.getData();
+ final int size = data.size();
+ final int newSize = size + len;
+ // Store the Exception in order to notify the client again on close()
+ try
+ {
+ this.file.resize(newSize);
+ }
+ catch (final IOException e)
+ {
+ this.exception = e;
+ throw e;
+ }
+ System.arraycopy(b, off, data.getContent(), size, len);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataOutput#write(int)
+ */
+ @Override
+ public void write(final int b) throws IOException
+ {
+ buffer1[0] = (byte) b;
+ this.write(buffer1);
+ }
+
+ @Override
+ public void flush() throws IOException
+ {
+ }
+
+ @Override
+ public void close() throws IOException
+ {
+ if (closed)
+ {
+ return;
+ }
+ // Notify on close that there was an IOException while writing
+ if (exception != null)
+ {
+ throw exception;
+ }
+ try
+ {
+ this.closed = true;
+ // Close the
+ this.file.endOutput();
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException(e);
+ }
+ }
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileProvider.java
new file mode 100644
index 0000000..d136232
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileProvider.java
@@ -0,0 +1,89 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ram;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider;
+import org.apache.commons.vfs2.provider.FileProvider;
+
+/**
+ * RAM File Provider.
+ */
+public class RamFileProvider extends AbstractOriginatingFileProvider implements
+ FileProvider
+{
+ /** The provider's capabilities. */
+ public static final Collection<Capability> capabilities = Collections
+ .unmodifiableCollection(Arrays.asList(new Capability[]
+ {
+ Capability.CREATE,
+ Capability.DELETE,
+ Capability.RENAME,
+ Capability.GET_TYPE,
+ Capability.GET_LAST_MODIFIED,
+ Capability.SET_LAST_MODIFIED_FILE,
+ Capability.SET_LAST_MODIFIED_FOLDER,
+ Capability.LIST_CHILDREN,
+ Capability.READ_CONTENT,
+ Capability.URI,
+ Capability.WRITE_CONTENT,
+ Capability.APPEND_CONTENT,
+ Capability.RANDOM_ACCESS_READ,
+ Capability.RANDOM_ACCESS_SET_LENGTH,
+ Capability.RANDOM_ACCESS_WRITE
+ }));
+
+ /**
+ * Constructs a new provider.
+ */
+ public RamFileProvider()
+ {
+ super();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider#doCreateFileSystem(
+ * org.apache.commons.vfs2.FileName, org.apache.commons.vfs2.FileSystemOptions)
+ */
+ @Override
+ protected FileSystem doCreateFileSystem(final FileName name,
+ final FileSystemOptions fileSystemOptions) throws FileSystemException
+ {
+ return new RamFileSystem(name, fileSystemOptions);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.commons.vfs2.provider.FileProvider#getCapabilities()
+ */
+ @Override
+ public Collection<Capability> getCapabilities()
+ {
+ return capabilities;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileRandomAccessContent.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileRandomAccessContent.java
new file mode 100644
index 0000000..7a9a2fc
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileRandomAccessContent.java
@@ -0,0 +1,652 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ram;
+
+import java.io.ByteArrayOutputStream;
+import java.io.DataInputStream;
+import java.io.DataOutputStream;
+import java.io.EOFException;
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.apache.commons.vfs2.RandomAccessContent;
+import org.apache.commons.vfs2.util.RandomAccessMode;
+
+/**
+ * RAM File Random Access Content.
+ */
+public class RamFileRandomAccessContent implements RandomAccessContent
+{
+ /**
+ * File Pointer
+ */
+ protected int filePointer = 0;
+
+ /**
+ * Buffer
+ */
+ private byte[] buf;
+
+ /**
+ * buffer
+ */
+ private final byte[] buffer8 = new byte[8];
+
+ /**
+ * buffer
+ */
+ private final byte[] buffer4 = new byte[4];
+
+ /**
+ * buffer
+ */
+ private final byte[] buffer2 = new byte[2];
+
+ /**
+ * buffer
+ */
+ private final byte[] buffer1 = new byte[1];
+
+ /**
+ * File
+ */
+ private final RamFileObject file;
+
+ private final InputStream rafis;
+
+ /**
+ * @param file The file to access.
+ * @param mode The access mode.
+ */
+ public RamFileRandomAccessContent(final RamFileObject file, final RandomAccessMode mode)
+ {
+ super();
+ this.buf = file.getData().getContent();
+ this.file = file;
+
+ rafis = new InputStream()
+ {
+ @Override
+ public int read() throws IOException
+ {
+ try
+ {
+ return readByte();
+ }
+ catch (final EOFException e)
+ {
+ return -1;
+ }
+ }
+
+ @Override
+ public long skip(final long n) throws IOException
+ {
+ seek(getFilePointer() + n);
+ return n;
+ }
+
+ @Override
+ public void close() throws IOException
+ {
+ }
+
+ @Override
+ public int read(final byte[] b) throws IOException
+ {
+ return read(b, 0, b.length);
+ }
+
+ @Override
+ public int read(final byte[] b, final int off, final int len) throws IOException
+ {
+ int retLen = -1;
+ final int left = getLeftBytes();
+ if (left > 0)
+ {
+ retLen = Math.min(len, left);
+ RamFileRandomAccessContent.this.readFully(b, off, retLen);
+ }
+ return retLen;
+ }
+
+ @Override
+ public int available() throws IOException
+ {
+ return getLeftBytes();
+ }
+ };
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.commons.vfs2.RandomAccessContent#getFilePointer()
+ */
+ @Override
+ public long getFilePointer() throws IOException
+ {
+ return this.filePointer;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.commons.vfs2.RandomAccessContent#seek(long)
+ */
+ @Override
+ public void seek(final long pos) throws IOException
+ {
+ if (pos < 0)
+ {
+ throw new IOException("Attempt to position before the start of the file");
+ }
+ this.filePointer = (int) pos;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.commons.vfs2.RandomAccessContent#length()
+ */
+ @Override
+ public long length() throws IOException
+ {
+ return buf.length;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.commons.vfs2.RandomAccessContent#close()
+ */
+ @Override
+ public void close() throws IOException
+ {
+
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataInput#readByte()
+ */
+ @Override
+ public byte readByte() throws IOException
+ {
+ return (byte) this.readUnsignedByte();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataInput#readChar()
+ */
+ @Override
+ public char readChar() throws IOException
+ {
+ final int ch1 = this.readUnsignedByte();
+ final int ch2 = this.readUnsignedByte();
+ return (char) ((ch1 << 8) + (ch2 << 0));
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataInput#readDouble()
+ */
+ @Override
+ public double readDouble() throws IOException
+ {
+ return Double.longBitsToDouble(this.readLong());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataInput#readFloat()
+ */
+ @Override
+ public float readFloat() throws IOException
+ {
+ return Float.intBitsToFloat(this.readInt());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataInput#readInt()
+ */
+ @Override
+ public int readInt() throws IOException
+ {
+ return (readUnsignedByte() << 24) | (readUnsignedByte() << 16)
+ | (readUnsignedByte() << 8) | readUnsignedByte();
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataInput#readUnsignedByte()
+ */
+ @Override
+ public int readUnsignedByte() throws IOException
+ {
+ if (filePointer < buf.length)
+ {
+ return buf[filePointer++] & 0xFF;
+ }
+ else
+ {
+ throw new EOFException();
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataInput#readUnsignedShort()
+ */
+ @Override
+ public int readUnsignedShort() throws IOException
+ {
+ this.readFully(buffer2);
+ return toUnsignedShort(buffer2);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataInput#readLong()
+ */
+ @Override
+ public long readLong() throws IOException
+ {
+ this.readFully(buffer8);
+ return toLong(buffer8);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataInput#readShort()
+ */
+ @Override
+ public short readShort() throws IOException
+ {
+ this.readFully(buffer2);
+ return toShort(buffer2);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataInput#readBoolean()
+ */
+ @Override
+ public boolean readBoolean() throws IOException
+ {
+ return this.readUnsignedByte() != 0;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataInput#skipBytes(int)
+ */
+ @Override
+ public int skipBytes(final int n) throws IOException
+ {
+ if (n < 0)
+ {
+ throw new IndexOutOfBoundsException(
+ "The skip number can't be negative");
+ }
+
+ final long newPos = filePointer + n;
+
+ if (newPos > buf.length)
+ {
+ throw new IndexOutOfBoundsException("Tyring to skip too much bytes");
+ }
+
+ seek(newPos);
+
+ return n;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataInput#readFully(byte[])
+ */
+ @Override
+ public void readFully(final byte[] b) throws IOException
+ {
+ this.readFully(b, 0, b.length);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataInput#readFully(byte[], int, int)
+ */
+ @Override
+ public void readFully(final byte[] b, final int off, final int len) throws IOException
+ {
+ if (len < 0)
+ {
+ throw new IndexOutOfBoundsException("Length is lower than 0");
+ }
+
+ if (len > this.getLeftBytes())
+ {
+ throw new IndexOutOfBoundsException("Read length (" + len
+ + ") is higher than buffer left bytes ("
+ + this.getLeftBytes() + ") ");
+ }
+
+ System.arraycopy(buf, filePointer, b, off, len);
+
+ filePointer += len;
+ }
+
+ private int getLeftBytes()
+ {
+ return buf.length - filePointer;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataInput#readUTF()
+ */
+ @Override
+ public String readUTF() throws IOException
+ {
+ return DataInputStream.readUTF(this);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataOutput#write(byte[], int, int)
+ */
+ @Override
+ public void write(final byte[] b, final int off, final int len) throws IOException
+ {
+ if (this.getLeftBytes() < len)
+ {
+ final int newSize = this.buf.length + len - this.getLeftBytes();
+ this.file.resize(newSize);
+ this.buf = this.file.getData().getContent();
+ }
+ System.arraycopy(b, off, this.buf, filePointer, len);
+ this.filePointer += len;
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataOutput#write(byte[])
+ */
+ @Override
+ public void write(final byte[] b) throws IOException
+ {
+ this.write(b, 0, b.length);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataOutput#writeByte(int)
+ */
+ @Override
+ public void writeByte(final int i) throws IOException
+ {
+ this.write(i);
+ }
+
+ /**
+ * Build a long from first 8 bytes of the array.
+ *
+ * @param b The byte[] to convert.
+ * @return A long.
+ */
+ public static long toLong(final byte[] b)
+ {
+ return ((((long) b[7]) & 0xFF) + ((((long) b[6]) & 0xFF) << 8)
+ + ((((long) b[5]) & 0xFF) << 16)
+ + ((((long) b[4]) & 0xFF) << 24)
+ + ((((long) b[3]) & 0xFF) << 32)
+ + ((((long) b[2]) & 0xFF) << 40)
+ + ((((long) b[1]) & 0xFF) << 48) + ((((long) b[0]) & 0xFF) << 56));
+ }
+
+ /**
+ * Build a 8-byte array from a long. No check is performed on the array
+ * length.
+ *
+ * @param n The number to convert.
+ * @param b The array to fill.
+ * @return A byte[].
+ */
+ public static byte[] toBytes(long n, final byte[] b)
+ {
+ b[7] = (byte) (n);
+ n >>>= 8;
+ b[6] = (byte) (n);
+ n >>>= 8;
+ b[5] = (byte) (n);
+ n >>>= 8;
+ b[4] = (byte) (n);
+ n >>>= 8;
+ b[3] = (byte) (n);
+ n >>>= 8;
+ b[2] = (byte) (n);
+ n >>>= 8;
+ b[1] = (byte) (n);
+ n >>>= 8;
+ b[0] = (byte) (n);
+ return b;
+ }
+
+ /**
+ * Build a short from first 2 bytes of the array.
+ * @param b The byte[] to convert.
+ * @return A short.
+ */
+ public static short toShort(final byte[] b)
+ {
+ return (short) toUnsignedShort(b);
+ }
+
+ /**
+ * Build a short from first 2 bytes of the array.
+ *
+ * @param b The byte[] to convert.
+ * @return A short.
+ */
+ public static int toUnsignedShort(final byte[] b)
+ {
+ return ((b[1] & 0xFF) + ((b[0] & 0xFF) << 8));
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataOutput#write(int)
+ */
+ @Override
+ public void write(final int b) throws IOException
+ {
+ buffer1[0] = (byte) b;
+ this.write(buffer1);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataOutput#writeBoolean(boolean)
+ */
+ @Override
+ public void writeBoolean(final boolean v) throws IOException
+ {
+ this.write(v ? 1 : 0);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataOutput#writeBytes(java.lang.String)
+ */
+ @Override
+ public void writeBytes(final String s) throws IOException
+ {
+ write(s.getBytes());
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataOutput#writeChar(int)
+ */
+ @Override
+ public void writeChar(final int v) throws IOException
+ {
+ buffer2[0] = (byte) ((v >>> 8) & 0xFF);
+ buffer2[1] = (byte) ((v >>> 0) & 0xFF);
+ write(buffer2);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataOutput#writeChars(java.lang.String)
+ */
+ @Override
+ public void writeChars(final String s) throws IOException
+ {
+ final int len = s.length();
+ for (int i = 0; i < len; i++)
+ {
+ writeChar(s.charAt(i));
+ }
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataOutput#writeDouble(double)
+ */
+ @Override
+ public void writeDouble(final double v) throws IOException
+ {
+ writeLong(Double.doubleToLongBits(v));
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataOutput#writeFloat(float)
+ */
+ @Override
+ public void writeFloat(final float v) throws IOException
+ {
+ writeInt(Float.floatToIntBits(v));
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataOutput#writeInt(int)
+ */
+ @Override
+ public void writeInt(final int v) throws IOException
+ {
+ buffer4[0] = (byte) ((v >>> 24) & 0xFF);
+ buffer4[1] = (byte) ((v >>> 16) & 0xFF);
+ buffer4[2] = (byte) ((v >>> 8) & 0xFF);
+ buffer4[3] = (byte) (v & 0xFF);
+ write(buffer4);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataOutput#writeLong(long)
+ */
+ @Override
+ public void writeLong(final long v) throws IOException
+ {
+ write(toBytes(v, buffer8));
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataOutput#writeShort(int)
+ */
+ @Override
+ public void writeShort(final int v) throws IOException
+ {
+ buffer2[0] = (byte) ((v >>> 8) & 0xFF);
+ buffer2[1] = (byte) (v & 0xFF);
+ write(buffer2);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataOutput#writeUTF(java.lang.String)
+ */
+ @Override
+ public void writeUTF(final String str) throws IOException
+ {
+ final ByteArrayOutputStream out = new ByteArrayOutputStream(str.length());
+ final DataOutputStream dataOut = new DataOutputStream(out);
+ dataOut.writeUTF(str);
+ dataOut.flush();
+ dataOut.close();
+ final byte[] b = out.toByteArray();
+ write(b);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see java.io.DataInput#readLine()
+ */
+ @Override
+ public String readLine() throws IOException
+ {
+ throw new UnsupportedOperationException("deprecated");
+ }
+
+ @Override
+ public InputStream getInputStream() throws IOException
+ {
+ return rafis;
+ }
+
+ @Override
+ public void setLength(final long newLength) throws IOException
+ {
+ this.file.resize(newLength);
+ this.buf = this.file.getData().getContent();
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileSystem.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileSystem.java
new file mode 100644
index 0000000..77050ea
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileSystem.java
@@ -0,0 +1,327 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ram;
+
+import java.io.BufferedOutputStream;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.Serializable;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.Map;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileSystem;
+
+/**
+ * A RAM File System.
+ */
+public class RamFileSystem extends AbstractFileSystem implements Serializable
+{
+ private static final int BUFFER_SIZE = 512;
+
+ /**
+ * serialVersionUID format is YYYYMMDD for the date of the last binary change.
+ */
+ private static final long serialVersionUID = 20101208L;
+
+ /**
+ * Cache of RAM File Data
+ */
+ private final Map<FileName, RamFileData> cache;
+
+ /**
+ * @param rootName The root file name.
+ * @param fileSystemOptions The FileSystem options.
+ */
+ protected RamFileSystem(final FileName rootName, final FileSystemOptions fileSystemOptions)
+ {
+ super(rootName, null, fileSystemOptions);
+ this.cache = Collections.synchronizedMap(new HashMap<FileName, RamFileData>());
+ // create root
+ final RamFileData rootData = new RamFileData(rootName);
+ rootData.setType(FileType.FOLDER);
+ rootData.setLastModified(System.currentTimeMillis());
+ this.cache.put(rootName, rootData);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.commons.vfs2.provider.AbstractFileSystem#createFile(org.apache.commons.vfs2.FileName)
+ */
+ @Override
+ protected FileObject createFile(final AbstractFileName name) throws Exception
+ {
+ return new RamFileObject(name, this);
+ }
+
+ /*
+ * (non-Javadoc)
+ *
+ * @see org.apache.commons.vfs2.provider.AbstractFileSystem#addCapabilities(java.util.Collection)
+ */
+ @Override
+ protected void addCapabilities(final Collection<Capability> caps)
+ {
+ caps.addAll(RamFileProvider.capabilities);
+ }
+
+ /**
+ * @param name The name of the file.
+ * @return children The names of the children.
+ */
+ String[] listChildren(final FileName name)
+ {
+ final RamFileData data = this.cache.get(name);
+ if (data == null || !data.getType().hasChildren())
+ {
+ return null;
+ }
+ final Collection<RamFileData> children = data.getChildren();
+ String[] names;
+
+ synchronized (children)
+ {
+ names = new String[children.size()];
+
+ int pos = 0;
+ final Iterator<RamFileData> iter = children.iterator();
+ while (iter.hasNext())
+ {
+ final RamFileData childData = iter.next();
+ names[pos] = childData.getName().getBaseName();
+ pos++;
+ }
+ }
+
+ return names;
+ }
+
+ /**
+ * Delete a file
+ *
+ * @param file
+ * @throws FileSystemException
+ */
+ void delete(final RamFileObject file) throws FileSystemException
+ {
+ // root is read only check
+ if (file.getParent() == null)
+ {
+ throw new FileSystemException("unable to delete root");
+ }
+
+ // Remove reference from cache
+ this.cache.remove(file.getName());
+ // Notify the parent
+ final RamFileObject parent = (RamFileObject) this.resolveFile(file
+ .getParent().getName());
+ parent.getData().removeChild(file.getData());
+ parent.close();
+ // Close the file
+ file.getData().clear();
+ file.close();
+ }
+
+ /**
+ * Saves a file
+ *
+ * @param file
+ * @throws FileSystemException
+ */
+ void save(final RamFileObject file) throws FileSystemException
+ {
+
+ // Validate name
+ if (file.getData().getName() == null)
+ {
+ throw new FileSystemException(new IllegalStateException(
+ "The data has no name. " + file));
+ }
+
+ // Add to the parent
+ if (file.getName().getDepth() > 0)
+ {
+ final RamFileData parentData = this.cache.get(file.getParent().getName());
+ // Only if not already added
+ if (!parentData.hasChildren(file.getData()))
+ {
+ final RamFileObject parent = (RamFileObject) file.getParent();
+ parent.getData().addChild(file.getData());
+ parent.close();
+ }
+ }
+ // Store in cache
+ cache.put(file.getName(), file.getData());
+ file.getData().updateLastModified();
+ file.close();
+ }
+
+ /**
+ * @param from The original file.
+ * @param to The new file.
+ * @throws FileSystemException if an error occurs.
+ */
+ void rename(final RamFileObject from, final RamFileObject to)
+ throws FileSystemException
+ {
+ if (!this.cache.containsKey(from.getName()))
+ {
+ throw new FileSystemException("File does not exist: "
+ + from.getName());
+ }
+ // Copy data
+
+ to.getData().setContent(from.getData().getContent());
+ to.getData().setLastModified(from.getData().getLastModified());
+ to.getData().setType(from.getData().getType());
+
+ this.save(to);
+ this.delete(from);
+ }
+
+ public void attach(final RamFileObject fo)
+ {
+ if (fo.getName() == null)
+ {
+ throw new IllegalArgumentException("Null argument");
+ }
+ RamFileData data = this.cache.get(fo.getName());
+ if (data == null)
+ {
+ data = new RamFileData(fo.getName());
+ }
+ fo.setData(data);
+ }
+
+ /**
+ * Import a Tree.
+ *
+ * @param file The File
+ * @throws FileSystemException if an error occurs.
+ */
+ public void importTree(final File file) throws FileSystemException
+ {
+ final FileObject fileFo = getFileSystemManager().toFileObject(file);
+ this.toRamFileObject(fileFo, fileFo);
+ }
+
+ /**
+ * Import the given file with the name relative to the given root
+ *
+ * @param fo
+ * @param root
+ * @throws FileSystemException
+ */
+ void toRamFileObject(final FileObject fo, final FileObject root)
+ throws FileSystemException
+ {
+ final RamFileObject memFo = (RamFileObject) this.resolveFile(fo.getName()
+ .getPath().substring(root.getName().getPath().length()));
+ if (fo.getType().hasChildren())
+ {
+ // Create Folder
+ memFo.createFolder();
+ // Import recursively
+ final FileObject[] fos = fo.getChildren();
+ for (final FileObject child : fos)
+ {
+ this.toRamFileObject(child, root);
+ }
+ }
+ else if (fo.isFile())
+ {
+ // Read bytes
+ try
+ {
+ final InputStream is = fo.getContent().getInputStream();
+ try
+ {
+ final OutputStream os = new BufferedOutputStream(memFo
+ .getOutputStream(), BUFFER_SIZE);
+ int i;
+ while ((i = is.read()) != -1)
+ {
+ os.write(i);
+ }
+ os.close();
+ }
+ finally
+ {
+ try
+ {
+ is.close();
+ }
+ catch (final IOException ignored)
+ {
+ /* ignore on close exception. */
+ }
+ // TODO: close os
+ }
+ }
+ catch (final IOException e)
+ {
+ throw new FileSystemException(e.getClass().getName() + " "
+ + e.getMessage());
+ }
+ }
+ else
+ {
+ throw new FileSystemException("File is not a folder nor a file "
+ + memFo);
+ }
+ }
+
+ /**
+ * @return Returns the size of the FileSystem
+ */
+ long size()
+ {
+ long size = 0;
+ synchronized (cache)
+ {
+ final Iterator<RamFileData> iter = cache.values().iterator();
+ while (iter.hasNext())
+ {
+ final RamFileData data = iter.next();
+ size += data.size();
+ }
+ }
+ return size;
+ }
+
+ /**
+ * Close the RAMFileSystem.
+ */
+ @Override
+ public void close()
+ {
+ this.cache.clear();
+ super.close();
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileSystemConfigBuilder.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileSystemConfigBuilder.java
new file mode 100644
index 0000000..4571b22
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileSystemConfigBuilder.java
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ram;
+
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemConfigBuilder;
+import org.apache.commons.vfs2.FileSystemOptions;
+
+/**
+ * Config Builder for the RAM filesystem.
+ */
+public final class RamFileSystemConfigBuilder extends FileSystemConfigBuilder
+{
+
+ /** max size key. */
+ private static final String MAX_SIZE_KEY = "maxsize";
+
+ /** config builder SINGLETON. */
+ private static final RamFileSystemConfigBuilder SINGLETON = new RamFileSystemConfigBuilder();
+
+ /**
+ * Constructor
+ */
+ private RamFileSystemConfigBuilder()
+ {
+ super("ram.");
+ }
+
+ /**
+ * Gets the singleton builder.
+ *
+ * @return the singleton builder.
+ */
+ public static RamFileSystemConfigBuilder getInstance()
+ {
+ return SINGLETON;
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ protected Class<? extends FileSystem> getConfigClass()
+ {
+ return RamFileSystem.class;
+ }
+
+ /**
+ * Defaults to {@link Integer#MAX_VALUE}.
+ *
+ * @param opts The FileSystem options.
+ * @return The maximum size of the file.
+ * @see #setMaxSize(FileSystemOptions, long)
+ * @since 2.1
+ */
+ public long getLongMaxSize(final FileSystemOptions opts)
+ {
+ return getLong(opts, MAX_SIZE_KEY, Long.MAX_VALUE);
+ }
+
+ /**
+ * Defaults to {@link Integer#MAX_VALUE}.
+ *
+ * @param opts The FileSystem options.
+ * @return The maximum size of the file. The next major version will change the return type to a long.
+ * @see #setMaxSize(FileSystemOptions, int)
+ */
+ public int getMaxSize(final FileSystemOptions opts)
+ {
+ return getLong(opts, MAX_SIZE_KEY, Long.valueOf(Integer.MAX_VALUE)).intValue();
+ }
+
+ /**
+ * Sets the maximum size of the file system.
+ *
+ * @param opts The FileSystem options.
+ * @param sizeInBytes The maximum file size.
+ * @deprecated Use {@link #setMaxSize(FileSystemOptions, long)}
+ */
+ @Deprecated
+ public void setMaxSize(final FileSystemOptions opts, final int sizeInBytes)
+ {
+ setParam(opts, MAX_SIZE_KEY, Long.valueOf(sizeInBytes));
+ }
+
+ /**
+ * Sets the maximum size of the file system.
+ *
+ * @param opts The FileSystem options.
+ * @param sizeInBytes The maximum file size.
+ */
+ public void setMaxSize(final FileSystemOptions opts, final long sizeInBytes)
+ {
+ setParam(opts, MAX_SIZE_KEY, Long.valueOf(sizeInBytes));
+ }
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/package.html
new file mode 100644
index 0000000..aca6904
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/ram/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>The RAM File Provider.</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/res/ResourceFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/res/ResourceFileProvider.java
new file mode 100644
index 0000000..325de04
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/res/ResourceFileProvider.java
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.res;
+
+import java.net.URL;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemConfigBuilder;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.AbstractFileProvider;
+import org.apache.commons.vfs2.provider.UriParser;
+
+/**
+ * The Resource provider.
+ */
+public class ResourceFileProvider extends AbstractFileProvider
+{
+ /** The provider's capabilities */
+ protected static final Collection<Capability> capabilities =
+ Collections.unmodifiableCollection(Arrays.asList(new Capability[]
+ {
+ Capability.DISPATCHER
+ }));
+
+ private static final int BUFFER_SIZE = 80;
+
+ public ResourceFileProvider()
+ {
+ super();
+ }
+
+ /**
+ * Locates a file object, by absolute URI.
+ * @param baseFile The base file.
+ * @param uri The URI of the file to locate.
+ * @param fileSystemOptions The FileSystem options.
+ * @return the FileObject.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public FileObject findFile(final FileObject baseFile,
+ final String uri,
+ final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ final StringBuilder buf = new StringBuilder(BUFFER_SIZE);
+ UriParser.extractScheme(uri, buf);
+ final String resourceName = buf.toString();
+
+ ClassLoader cl = ResourceFileSystemConfigBuilder.getInstance().getClassLoader(fileSystemOptions);
+ if (cl == null)
+ {
+ cl = getClass().getClassLoader();
+ }
+ final URL url = cl.getResource(resourceName);
+
+ if (url == null)
+ {
+ throw new FileSystemException("vfs.provider.url/badly-formed-uri.error", uri);
+ }
+
+ return getContext().getFileSystemManager().resolveFile(url.toExternalForm());
+ }
+
+ @Override
+ public FileSystemConfigBuilder getConfigBuilder()
+ {
+ return org.apache.commons.vfs2.provider.res.ResourceFileSystemConfigBuilder.getInstance();
+ }
+
+ @Override
+ public void closeFileSystem(final FileSystem filesystem)
+ {
+ // no filesystem created here - so nothing to do
+ }
+
+ @Override
+ public Collection<Capability> getCapabilities()
+ {
+ return capabilities;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/res/ResourceFileSystemConfigBuilder.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/res/ResourceFileSystemConfigBuilder.java
new file mode 100644
index 0000000..e73768f
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/res/ResourceFileSystemConfigBuilder.java
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.res;
+
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemConfigBuilder;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.url.UrlFileSystem;
+
+/**
+ * The config BUILDER for various ftp configuration options.
+ */
+public final class ResourceFileSystemConfigBuilder extends FileSystemConfigBuilder
+{
+ private static final ResourceFileSystemConfigBuilder BUILDER = new ResourceFileSystemConfigBuilder();
+
+ private ResourceFileSystemConfigBuilder()
+ {
+ super("resource.");
+ }
+
+ /**
+ * Gets the singleton builder.
+ *
+ * @return the singleton builder.
+ */
+ public static ResourceFileSystemConfigBuilder getInstance()
+ {
+ return BUILDER;
+ }
+
+
+ public void setClassLoader(final FileSystemOptions opts, final ClassLoader classLoader)
+ {
+ setParam(opts, ClassLoader.class.getName(), classLoader);
+ }
+
+ public ClassLoader getClassLoader(final FileSystemOptions opts)
+ {
+ return (ClassLoader) getParam(opts, ClassLoader.class.getName());
+ }
+
+ @Override
+ protected Class<? extends FileSystem> getConfigClass()
+ {
+ return UrlFileSystem.class;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/res/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/res/package.html
new file mode 100644
index 0000000..64dfc9f
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/res/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>The Resource File Provider</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/IdentityInfo.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/IdentityInfo.java
new file mode 100644
index 0000000..cd7cb6b
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/IdentityInfo.java
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.sftp;
+
+import java.io.File;
+
+
+/**
+ * Structure for an identity.
+ *
+ * @since 2.1
+ */
+public class IdentityInfo
+{
+ private final File privateKey;
+ private final File publicKey;
+ private final byte[] passPhrase;
+
+ /**
+ * Constructs an identity info with private key.
+ * <p>
+ * The key is not passphrase protected.
+ * <p>
+ * We use java.io.File because JSch cannot deal with VFS FileObjects.
+ *
+ * @param privateKey The file with the private key
+ * @since 2.1
+ */
+ public IdentityInfo(final File privateKey)
+ {
+ this(privateKey, null, null);
+ }
+
+ /**
+ * Constructs an identity info with private key and its passphrase.
+ * <p>
+ * We use java.io.File because JSch cannot deal with VFS FileObjects.
+ *
+ * @param privateKey The file with the private key
+ * @param passPhrase The passphrase to decrypt the private key (can be {@code null} if no passphrase is used)
+ * @since 2.1
+ */
+ public IdentityInfo(final File privateKey, final byte[] passPhrase)
+ {
+ this(privateKey, null, passPhrase);
+ }
+
+ /**
+ * Constructs an identity info with private and public key and passphrase for the private key.
+ * <p>
+ * We use java.io.File because JSch cannot deal with VFS FileObjects.
+ *
+ * @param privateKey The file with the private key
+ * @param publicKey The public key part used for connections with exchange of certificates (can be {@code null})
+ * @param passPhrase The passphrase to decrypt the private key (can be {@code null} if no passphrase is used)
+ * @since 2.1
+ */
+ public IdentityInfo(final File privateKey, final File publicKey, final byte[] passPhrase)
+ {
+ this.privateKey = privateKey;
+ this.publicKey = publicKey;
+ this.passPhrase = passPhrase;
+ }
+
+ /**
+ * Get the file with the private key.
+ *
+ * @return the file
+ * @since 2.1
+ */
+ public File getPrivateKey()
+ {
+ return privateKey;
+ }
+
+ /**
+ * Get the file with the public key.
+ *
+ * @return the file
+ * @since 2.1
+ */
+ public File getPublicKey()
+ {
+ return publicKey;
+ }
+
+ /**
+ * Get the passphrase of the private key.
+ *
+ * @return the passphrase
+ * @since 2.1
+ */
+ public byte[] getPassPhrase()
+ {
+ return passPhrase;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/IdentityRepositoryFactory.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/IdentityRepositoryFactory.java
new file mode 100644
index 0000000..627b2dc
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/IdentityRepositoryFactory.java
@@ -0,0 +1,37 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.sftp;
+
+import com.jcraft.jsch.IdentityRepository;
+import com.jcraft.jsch.JSch;
+
+/**
+ * Creates instances of JSch {@link IdentityRepository}.
+ *
+ * @version $Id$
+ */
+public interface IdentityRepositoryFactory
+{
+ /**
+ * Creates an Identity repository for a given JSch instance.
+ *
+ * @param jsch
+ * JSch context
+ * @return a new IdentityRepository
+ */
+ IdentityRepository create(JSch jsch);
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpClientFactory.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpClientFactory.java
new file mode 100644
index 0000000..cdd0e1b
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpClientFactory.java
@@ -0,0 +1,369 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.sftp;
+
+import java.io.File;
+import java.util.Properties;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.util.Os;
+
+import com.jcraft.jsch.JSch;
+import com.jcraft.jsch.JSchException;
+import com.jcraft.jsch.Logger;
+import com.jcraft.jsch.Proxy;
+import com.jcraft.jsch.ProxyHTTP;
+import com.jcraft.jsch.ProxySOCKS5;
+import com.jcraft.jsch.Session;
+import com.jcraft.jsch.UserInfo;
+
+/**
+ * Create a JSch Session instance.
+ */
+public final class SftpClientFactory
+{
+ private static final String SSH_DIR_NAME = ".ssh";
+
+ private static final Log LOG = LogFactory.getLog(SftpClientFactory.class);
+
+ static
+ {
+ JSch.setLogger(new JSchLogger());
+ }
+
+ private SftpClientFactory()
+ {
+ }
+
+ /**
+ * Creates a new connection to the server.
+ *
+ * @param hostname The name of the host to connect to.
+ * @param port The port to use.
+ * @param username The user's id.
+ * @param password The user's password.
+ * @param fileSystemOptions The FileSystem options.
+ * @return A Session.
+ * @throws FileSystemException if an error occurs.
+ */
+ public static Session createConnection(final String hostname, final int port, final char[] username,
+ final char[] password, final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ final JSch jsch = new JSch();
+
+ File sshDir = null;
+
+ // new style - user passed
+ final SftpFileSystemConfigBuilder builder = SftpFileSystemConfigBuilder.getInstance();
+ final File knownHostsFile = builder.getKnownHosts(fileSystemOptions);
+ final IdentityInfo[] identities = builder.getIdentityInfo(fileSystemOptions);
+ final IdentityRepositoryFactory repositoryFactory = builder.getIdentityRepositoryFactory(fileSystemOptions);
+
+ sshDir = findSshDir();
+
+ setKnownHosts(jsch, sshDir, knownHostsFile);
+
+ if (repositoryFactory != null)
+ {
+ jsch.setIdentityRepository(repositoryFactory.create(jsch));
+ }
+
+ addIdentities(jsch, sshDir, identities);
+
+ Session session;
+ try
+ {
+ session = jsch.getSession(new String(username), hostname, port);
+ if (password != null)
+ {
+ session.setPassword(new String(password));
+ }
+
+ final Integer timeout = builder.getTimeout(fileSystemOptions);
+ if (timeout != null)
+ {
+ session.setTimeout(timeout.intValue());
+ }
+
+ final UserInfo userInfo = builder.getUserInfo(fileSystemOptions);
+ if (userInfo != null)
+ {
+ session.setUserInfo(userInfo);
+ }
+
+ final Properties config = new Properties();
+
+ // set StrictHostKeyChecking property
+ final String strictHostKeyChecking = builder.getStrictHostKeyChecking(fileSystemOptions);
+ if (strictHostKeyChecking != null)
+ {
+ config.setProperty("StrictHostKeyChecking", strictHostKeyChecking);
+ }
+ // set PreferredAuthentications property
+ final String preferredAuthentications = builder.getPreferredAuthentications(fileSystemOptions);
+ if (preferredAuthentications != null)
+ {
+ config.setProperty("PreferredAuthentications", preferredAuthentications);
+ }
+
+ // set compression property
+ final String compression = builder.getCompression(fileSystemOptions);
+ if (compression != null)
+ {
+ config.setProperty("compression.s2c", compression);
+ config.setProperty("compression.c2s", compression);
+ }
+
+ final String proxyHost = builder.getProxyHost(fileSystemOptions);
+ if (proxyHost != null)
+ {
+ final int proxyPort = builder.getProxyPort(fileSystemOptions);
+ final SftpFileSystemConfigBuilder.ProxyType proxyType = builder.getProxyType(fileSystemOptions);
+ Proxy proxy = null;
+ if (SftpFileSystemConfigBuilder.PROXY_HTTP.equals(proxyType))
+ {
+ proxy = createProxyHTTP(proxyHost, proxyPort);
+ }
+ else if (SftpFileSystemConfigBuilder.PROXY_SOCKS5.equals(proxyType))
+ {
+ proxy = createProxySOCKS5(proxyHost, proxyPort);
+ }
+ else if (SftpFileSystemConfigBuilder.PROXY_STREAM.equals(proxyType))
+ {
+ proxy = createStreamProxy(proxyHost, proxyPort, fileSystemOptions, builder);
+ }
+
+ if (proxy != null)
+ {
+ session.setProxy(proxy);
+ }
+ }
+
+ // set properties for the session
+ if (config.size() > 0)
+ {
+ session.setConfig(config);
+ }
+ session.setDaemonThread(true);
+ session.connect();
+ }
+ catch (final Exception exc)
+ {
+ throw new FileSystemException("vfs.provider.sftp/connect.error", exc, hostname);
+ }
+
+ return session;
+ }
+
+ private static void addIdentities(final JSch jsch, final File sshDir, final IdentityInfo[] identities)
+ throws FileSystemException
+ {
+ if (identities != null)
+ {
+ for (final IdentityInfo info : identities)
+ {
+ addIndentity(jsch, info);
+ }
+ }
+ else
+ {
+ // Load the private key (rsa-key only)
+ final File privateKeyFile = new File(sshDir, "id_rsa");
+ if (privateKeyFile.isFile() && privateKeyFile.canRead())
+ {
+ addIndentity(jsch, new IdentityInfo(privateKeyFile));
+ }
+ }
+ }
+
+ private static void addIndentity(final JSch jsch, final IdentityInfo info)
+ throws FileSystemException
+ {
+ try
+ {
+ final String privateKeyFile = info.getPrivateKey() != null ? info.getPrivateKey().getAbsolutePath() : null;
+ final String publicKeyFile = info.getPublicKey() != null ? info.getPublicKey().getAbsolutePath() : null;
+ jsch.addIdentity(privateKeyFile, publicKeyFile, info.getPassPhrase());
+ }
+ catch (final JSchException e)
+ {
+ throw new FileSystemException("vfs.provider.sftp/load-private-key.error", info, e);
+ }
+ }
+
+ private static void setKnownHosts(final JSch jsch, final File sshDir, File knownHostsFile)
+ throws FileSystemException
+ {
+ try
+ {
+ if (knownHostsFile != null)
+ {
+ jsch.setKnownHosts(knownHostsFile.getAbsolutePath());
+ }
+ else
+ {
+ // Load the known hosts file
+ knownHostsFile = new File(sshDir, "known_hosts");
+ if (knownHostsFile.isFile() && knownHostsFile.canRead())
+ {
+ jsch.setKnownHosts(knownHostsFile.getAbsolutePath());
+ }
+ }
+ }
+ catch (final JSchException e)
+ {
+ throw new FileSystemException("vfs.provider.sftp/known-hosts.error", knownHostsFile.getAbsolutePath(), e);
+ }
+
+ }
+
+ private static Proxy createStreamProxy(final String proxyHost, final int proxyPort,
+ final FileSystemOptions fileSystemOptions,
+ final SftpFileSystemConfigBuilder builder)
+ {
+ Proxy proxy;
+ // Use a stream proxy, i.e. it will use a remote host as a proxy
+ // and run a command (e.g. netcat) that forwards input/output
+ // to the target host.
+
+ // Here we get the settings for connecting to the proxy:
+ // user, password, options and a command
+ final String proxyUser = builder.getProxyUser(fileSystemOptions);
+ final String proxyPassword = builder.getProxyPassword(fileSystemOptions);
+ final FileSystemOptions proxyOptions = builder.getProxyOptions(fileSystemOptions);
+
+ final String proxyCommand = builder.getProxyCommand(fileSystemOptions);
+
+ // Create the stream proxy
+ proxy = new SftpStreamProxy(proxyCommand, proxyUser, proxyHost, proxyPort, proxyPassword, proxyOptions);
+ return proxy;
+ }
+
+ private static ProxySOCKS5 createProxySOCKS5(final String proxyHost, final int proxyPort)
+ {
+ return proxyPort == 0 ? new ProxySOCKS5(proxyHost) : new ProxySOCKS5(proxyHost, proxyPort);
+ }
+
+ private static ProxyHTTP createProxyHTTP(final String proxyHost, final int proxyPort)
+ {
+ return proxyPort == 0 ? new ProxyHTTP(proxyHost) : new ProxyHTTP(proxyHost, proxyPort);
+ }
+
+ /**
+ * Finds the .ssh directory.
+ * <p>
+ * The lookup order is:
+ * <ol>
+ * <li>The system property {@code vfs.sftp.sshdir} (the override
+ * mechanism)</li>
+ * <li>{user.home}/.ssh</li>
+ * <li>On Windows only: C:\cygwin\home\{user.name}\.ssh</li>
+ * <li>The current directory, as a last resort.</li>
+ * <ol>
+ * Windows Notes:<br>
+ * The default installation directory for Cygwin is {@code C:\cygwin}.
+ * On my set up (Gary here), I have Cygwin in C:\bin\cygwin, not the default.
+ * Also, my .ssh directory was created in the {user.home} directory.
+ *
+ * @return The .ssh directory
+ */
+ private static File findSshDir()
+ {
+ String sshDirPath;
+ sshDirPath = System.getProperty("vfs.sftp.sshdir");
+ if (sshDirPath != null)
+ {
+ final File sshDir = new File(sshDirPath);
+ if (sshDir.exists())
+ {
+ return sshDir;
+ }
+ }
+
+ File sshDir = new File(System.getProperty("user.home"), SSH_DIR_NAME);
+ if (sshDir.exists())
+ {
+ return sshDir;
+ }
+
+ if (Os.isFamily(Os.OS_FAMILY_WINDOWS))
+ {
+ // TODO - this may not be true
+ final String userName = System.getProperty("user.name");
+ sshDir = new File("C:\\cygwin\\home\\" + userName + "\\" + SSH_DIR_NAME);
+ if (sshDir.exists())
+ {
+ return sshDir;
+ }
+ }
+ return new File("");
+ }
+
+ /** Interface JSchLogger with JCL. */
+ private static class JSchLogger implements Logger
+ {
+ @Override
+ public boolean isEnabled(final int level)
+ {
+ switch (level)
+ {
+ case FATAL:
+ return LOG.isFatalEnabled();
+ case ERROR:
+ return LOG.isErrorEnabled();
+ case WARN:
+ return LOG.isDebugEnabled();
+ case DEBUG:
+ return LOG.isDebugEnabled();
+ case INFO:
+ return LOG.isInfoEnabled();
+ default:
+ return LOG.isDebugEnabled();
+
+ }
+ }
+
+ @Override
+ public void log(final int level, final String msg)
+ {
+ switch (level)
+ {
+ case FATAL:
+ LOG.fatal(msg);
+ break;
+ case ERROR:
+ LOG.error(msg);
+ break;
+ case WARN:
+ LOG.warn(msg);
+ break;
+ case DEBUG:
+ LOG.debug(msg);
+ break;
+ case INFO:
+ LOG.info(msg);
+ break;
+ default:
+ LOG.debug(msg);
+ }
+ }
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpFileNameParser.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpFileNameParser.java
new file mode 100644
index 0000000..c0ab465
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpFileNameParser.java
@@ -0,0 +1,48 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.sftp;
+
+import org.apache.commons.vfs2.provider.FileNameParser;
+import org.apache.commons.vfs2.provider.URLFileNameParser;
+
+/**
+ * Implementation for SFTP. Sets the default port to 22.
+ */
+public class SftpFileNameParser extends URLFileNameParser
+{
+ private static final int DEFAULT_PORT = 22;
+
+ private static final SftpFileNameParser INSTANCE = new SftpFileNameParser();
+
+ /**
+ * Creates a new instance with a the default port 22.
+ */
+ public SftpFileNameParser()
+ {
+ super(DEFAULT_PORT);
+ }
+
+ /**
+ * Gets the singleton instance.
+ *
+ * @return the singleton instance.
+ */
+ public static FileNameParser getInstance()
+ {
+ return INSTANCE;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpFileObject.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpFileObject.java
new file mode 100644
index 0000000..a3d5617
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpFileObject.java
@@ -0,0 +1,686 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.sftp;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.Vector;
+
+import org.apache.commons.vfs2.FileNotFoundException;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.NameScope;
+import org.apache.commons.vfs2.RandomAccessContent;
+import org.apache.commons.vfs2.VFS;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileObject;
+import org.apache.commons.vfs2.provider.UriParser;
+import org.apache.commons.vfs2.util.FileObjectUtils;
+import org.apache.commons.vfs2.util.MonitorInputStream;
+import org.apache.commons.vfs2.util.MonitorOutputStream;
+import org.apache.commons.vfs2.util.PosixPermissions;
+import org.apache.commons.vfs2.util.RandomAccessMode;
+
+import com.jcraft.jsch.ChannelSftp;
+import com.jcraft.jsch.ChannelSftp.LsEntry;
+import com.jcraft.jsch.SftpATTRS;
+import com.jcraft.jsch.SftpException;
+
+/**
+ * An SFTP file.
+ */
+public class SftpFileObject extends AbstractFileObject<SftpFileSystem>
+{
+ private static final long MOD_TIME_FACTOR = 1000L;
+
+ private SftpATTRS attrs;
+ private final String relPath;
+
+ private boolean inRefresh;
+
+ protected SftpFileObject(final AbstractFileName name,
+ final SftpFileSystem fileSystem) throws FileSystemException
+ {
+ super(name, fileSystem);
+ relPath = UriParser.decode(fileSystem.getRootName().getRelativeName(
+ name));
+ }
+
+ /** @since 2.0 */
+ @Override
+ protected void doDetach() throws Exception
+ {
+ attrs = null;
+ }
+
+ /**
+ * @throws FileSystemException if error occurs.
+ * @since 2.0
+ */
+ @Override
+ public void refresh() throws FileSystemException
+ {
+ if (!inRefresh)
+ {
+ try
+ {
+ inRefresh = true;
+ super.refresh();
+ try
+ {
+ attrs = null;
+ getType();
+ }
+ catch (final IOException e)
+ {
+ throw new FileSystemException(e);
+ }
+ }
+ finally
+ {
+ inRefresh = false;
+ }
+ }
+ }
+
+ /**
+ * Determines the type of this file, returns null if the file does not
+ * exist.
+ */
+ @Override
+ protected FileType doGetType() throws Exception
+ {
+ if (attrs == null)
+ {
+ statSelf();
+ }
+
+ if (attrs == null)
+ {
+ return FileType.IMAGINARY;
+ }
+
+ if ((attrs.getFlags() & SftpATTRS.SSH_FILEXFER_ATTR_PERMISSIONS) == 0)
+ {
+ throw new FileSystemException(
+ "vfs.provider.sftp/unknown-permissions.error");
+ }
+ if (attrs.isDir())
+ {
+ return FileType.FOLDER;
+ }
+ else
+ {
+ return FileType.FILE;
+ }
+ }
+
+ /**
+ * Called when the type or content of this file changes.
+ */
+ @Override
+ protected void onChange() throws Exception
+ {
+ statSelf();
+ }
+
+ /**
+ * Fetches file attributes from server.
+ *
+ * @throws IOException
+ */
+ private void statSelf() throws IOException
+ {
+ ChannelSftp channel = getAbstractFileSystem().getChannel();
+ try
+ {
+ setStat(channel.stat(relPath));
+ }
+ catch (final SftpException e)
+ {
+ try
+ {
+ // maybe the channel has some problems, so recreate the channel and retry
+ if (e.id != ChannelSftp.SSH_FX_NO_SUCH_FILE)
+ {
+ channel.disconnect();
+ channel = getAbstractFileSystem().getChannel();
+ setStat(channel.stat(relPath));
+ }
+ else
+ {
+ // Really does not exist
+ attrs = null;
+ }
+ }
+ catch (final SftpException innerEx)
+ {
+ // TODO - not strictly true, but jsch 0.1.2 does not give us
+ // enough info in the exception. Should be using:
+ // if ( e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE )
+ // However, sometimes the exception has the correct id, and
+ // sometimes
+ // it does not. Need to look into why.
+
+ // Does not exist
+ attrs = null;
+ }
+ }
+ finally
+ {
+ getAbstractFileSystem().putChannel(channel);
+ }
+ }
+
+ /**
+ * Set attrs from listChildrenResolved
+ */
+ private void setStat(final SftpATTRS attrs)
+ {
+ this.attrs = attrs;
+ }
+
+ /**
+ * Creates this file as a folder.
+ */
+ @Override
+ protected void doCreateFolder() throws Exception
+ {
+ final ChannelSftp channel = getAbstractFileSystem().getChannel();
+ try
+ {
+ channel.mkdir(relPath);
+ }
+ finally
+ {
+ getAbstractFileSystem().putChannel(channel);
+ }
+ }
+
+ @Override
+ protected long doGetLastModifiedTime() throws Exception
+ {
+ if (attrs == null
+ || (attrs.getFlags() & SftpATTRS.SSH_FILEXFER_ATTR_ACMODTIME) == 0)
+ {
+ throw new FileSystemException(
+ "vfs.provider.sftp/unknown-modtime.error");
+ }
+ return attrs.getMTime() * MOD_TIME_FACTOR;
+ }
+
+ /**
+ * Sets the last modified time of this file. Is only called if
+ * {@link #doGetType} does not return {@link FileType#IMAGINARY}.
+ *
+ * @param modtime
+ * is modification time in milliseconds. SFTP protocol can send
+ * times with nanosecond precision but at the moment jsch send
+ * them with second precision.
+ */
+ @Override
+ protected boolean doSetLastModifiedTime(final long modtime) throws Exception
+ {
+ final int newMTime = (int) (modtime / MOD_TIME_FACTOR);
+ attrs.setACMODTIME(attrs.getATime(), newMTime);
+ flushStat();
+ return true;
+ }
+
+ private void flushStat() throws IOException, SftpException
+ {
+ final ChannelSftp channel = getAbstractFileSystem().getChannel();
+ try
+ {
+ channel.setStat(relPath, attrs);
+ }
+ finally
+ {
+ getAbstractFileSystem().putChannel(channel);
+ }
+ }
+
+ /**
+ * Deletes the file.
+ */
+ @Override
+ protected void doDelete() throws Exception
+ {
+ final ChannelSftp channel = getAbstractFileSystem().getChannel();
+ try
+ {
+ if (isFile())
+ {
+ channel.rm(relPath);
+ }
+ else
+ {
+ channel.rmdir(relPath);
+ }
+ }
+ finally
+ {
+ getAbstractFileSystem().putChannel(channel);
+ }
+ }
+
+ /**
+ * Rename the file.
+ */
+ @Override
+ protected void doRename(final FileObject newFile) throws Exception
+ {
+ final ChannelSftp channel = getAbstractFileSystem().getChannel();
+ try
+ {
+ final SftpFileObject newSftpFileObject = (SftpFileObject) FileObjectUtils.getAbstractFileObject(newFile);
+ channel.rename(relPath, newSftpFileObject.relPath);
+ }
+ finally
+ {
+ getAbstractFileSystem().putChannel(channel);
+ }
+ }
+
+ /**
+ * Returns the POSIX type permissions of the file.
+ *
+ * @param checkIds {@code true} if user and group ID should be checked (needed for some access rights checks)
+ * @return A PosixPermission object
+ * @throws Exception If an error occurs
+ * @since 2.1
+ */
+ protected PosixPermissions getPermissions(final boolean checkIds) throws Exception
+ {
+ statSelf();
+ boolean isInGroup = false;
+ if (checkIds)
+ {
+ for (final int groupId : getAbstractFileSystem().getGroupsIds())
+ {
+ if (groupId == attrs.getGId())
+ {
+ isInGroup = true;
+ break;
+ }
+ }
+ }
+ final boolean isOwner = checkIds ? attrs.getUId() == getAbstractFileSystem().getUId() : false;
+ final PosixPermissions permissions = new PosixPermissions(attrs.getPermissions(), isOwner, isInGroup);
+
+ return permissions;
+ }
+
+ @Override
+ protected boolean doIsReadable() throws Exception
+ {
+ return getPermissions(true).isReadable();
+ }
+
+ @Override
+ protected boolean doSetReadable(final boolean readable, final boolean ownerOnly) throws Exception
+ {
+ final PosixPermissions permissions = getPermissions(false);
+ final int newPermissions = permissions.makeReadable(readable, ownerOnly);
+ if (newPermissions == permissions.getPermissions())
+ {
+ return true;
+ }
+
+ attrs.setPERMISSIONS(newPermissions);
+ flushStat();
+
+ return true;
+ }
+
+ @Override
+ protected boolean doIsWriteable() throws Exception
+ {
+ return getPermissions(true).isWritable();
+ }
+
+ @Override
+ protected boolean doSetWritable(final boolean writable, final boolean ownerOnly) throws Exception
+ {
+ final PosixPermissions permissions = getPermissions(false);
+ final int newPermissions = permissions.makeWritable(writable, ownerOnly);
+ if (newPermissions == permissions.getPermissions())
+ {
+ return true;
+ }
+
+ attrs.setPERMISSIONS(newPermissions);
+ flushStat();
+
+ return true;
+ }
+
+ @Override
+ protected boolean doIsExecutable() throws Exception
+ {
+ return getPermissions(true).isExecutable();
+ }
+
+
+ @Override
+ protected boolean doSetExecutable(final boolean executable, final boolean ownerOnly) throws Exception
+ {
+ final PosixPermissions permissions = getPermissions(false);
+ final int newPermissions = permissions.makeExecutable(executable, ownerOnly);
+ if (newPermissions == permissions.getPermissions())
+ {
+ return true;
+ }
+
+ attrs.setPERMISSIONS(newPermissions);
+ flushStat();
+
+ return true;
+ }
+
+ /**
+ * Lists the children of this file.
+ */
+ @Override
+ protected FileObject[] doListChildrenResolved() throws Exception
+ {
+ // should not require a round-trip because type is already set.
+ if (this.isFile())
+ {
+ return null;
+ }
+ // List the contents of the folder
+ Vector<?> vector = null;
+ final ChannelSftp channel = getAbstractFileSystem().getChannel();
+
+ try
+ {
+ // try the direct way to list the directory on the server to avoid too many roundtrips
+ vector = channel.ls(relPath);
+ }
+ catch (final SftpException e)
+ {
+ String workingDirectory = null;
+ try
+ {
+ if (relPath != null)
+ {
+ workingDirectory = channel.pwd();
+ channel.cd(relPath);
+ }
+ }
+ catch (final SftpException ex)
+ {
+ // VFS-210: seems not to be a directory
+ return null;
+ }
+
+ SftpException lsEx = null;
+ try
+ {
+ vector = channel.ls(".");
+ }
+ catch (final SftpException ex)
+ {
+ lsEx = ex;
+ }
+ finally
+ {
+ try
+ {
+ if (relPath != null)
+ {
+ channel.cd(workingDirectory);
+ }
+ }
+ catch (final SftpException xe)
+ {
+ throw new FileSystemException("vfs.provider.sftp/change-work-directory-back.error",
+ workingDirectory, lsEx);
+ }
+ }
+
+ if (lsEx != null)
+ {
+ throw lsEx;
+ }
+ }
+ finally
+ {
+ getAbstractFileSystem().putChannel(channel);
+ }
+ if (vector == null)
+ {
+ throw new FileSystemException(
+ "vfs.provider.sftp/list-children.error");
+ }
+
+ // Extract the child names
+ final ArrayList<FileObject> children = new ArrayList<FileObject>();
+ for (@SuppressWarnings("unchecked") // OK because ChannelSftp.ls() is documented to return Vector<LsEntry>
+ final
+ Iterator<LsEntry> iterator = (Iterator<LsEntry>) vector.iterator(); iterator.hasNext();)
+ {
+ final LsEntry stat = iterator.next();
+
+ String name = stat.getFilename();
+ if (VFS.isUriStyle() && stat.getAttrs().isDir()
+ && name.charAt(name.length() - 1) != '/')
+ {
+ name = name + "/";
+ }
+
+ if (name.equals(".") || name.equals("..") || name.equals("./")
+ || name.equals("../"))
+ {
+ continue;
+ }
+
+ final FileObject fo =
+ getFileSystem()
+ .resolveFile(
+ getFileSystem().getFileSystemManager().resolveName(
+ getName(), UriParser.encode(name),
+ NameScope.CHILD));
+
+ ((SftpFileObject) FileObjectUtils.getAbstractFileObject(fo)).setStat(stat.getAttrs());
+
+ children.add(fo);
+ }
+
+ return children.toArray(new FileObject[children.size()]);
+ }
+
+ /**
+ * Lists the children of this file.
+ */
+ @Override
+ protected String[] doListChildren() throws Exception
+ {
+ // use doListChildrenResolved for performance
+ return null;
+ }
+
+ /**
+ * Returns the size of the file content (in bytes).
+ */
+ @Override
+ protected long doGetContentSize() throws Exception
+ {
+ if (attrs == null
+ || (attrs.getFlags() & SftpATTRS.SSH_FILEXFER_ATTR_SIZE) == 0)
+ {
+ throw new FileSystemException(
+ "vfs.provider.sftp/unknown-size.error");
+ }
+ return attrs.getSize();
+ }
+
+ @Override
+ protected RandomAccessContent doGetRandomAccessContent(
+ final RandomAccessMode mode) throws Exception
+ {
+ return new SftpRandomAccessContent(this, mode);
+ }
+
+ /**
+ * Creates an input stream to read the file content from.
+ * The input stream is starting at the given position in the file.
+ */
+ InputStream getInputStream(final long filePointer) throws IOException
+ {
+ final ChannelSftp channel = getAbstractFileSystem().getChannel();
+ // Using InputStream directly from the channel
+ // is much faster than the memory method.
+ try
+ {
+ final InputStream is = channel.get(getName().getPathDecoded(), null, filePointer);
+ return new SftpInputStream(channel, is);
+ }
+ catch (final SftpException e)
+ {
+ getAbstractFileSystem().putChannel(channel);
+ throw new FileSystemException(e);
+ }
+ }
+
+ /**
+ * Creates an input stream to read the file content from.
+ */
+ @Override
+ protected InputStream doGetInputStream() throws Exception
+ {
+ // VFS-113: avoid npe
+ synchronized (getAbstractFileSystem())
+ {
+ final ChannelSftp channel = getAbstractFileSystem().getChannel();
+ try
+ {
+ // return channel.get(getName().getPath());
+ // hmmm - using the in memory method is soooo much faster ...
+
+ // TODO - Don't read the entire file into memory. Use the
+ // stream-based methods on ChannelSftp once they work properly
+
+ /*
+ final ByteArrayOutputStream outstr = new ByteArrayOutputStream();
+ channel.get(relPath, outstr);
+ outstr.close();
+ return new ByteArrayInputStream(outstr.toByteArray());
+ */
+
+ InputStream is;
+ try
+ {
+ // VFS-210: sftp allows to gather an input stream even from a directory and will
+ // fail on first read. So we need to check the type anyway
+ if (!getType().hasContent())
+ {
+ throw new FileSystemException("vfs.provider/read-not-file.error", getName());
+ }
+
+ is = channel.get(relPath);
+ }
+ catch (final SftpException e)
+ {
+ if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE)
+ {
+ throw new FileNotFoundException(getName());
+ }
+
+ throw new FileSystemException(e);
+ }
+
+ return new SftpInputStream(channel, is);
+
+ }
+ finally
+ {
+// getAbstractFileSystem().putChannel(channel);
+ }
+ }
+ }
+
+ /**
+ * Creates an output stream to write the file content to.
+ */
+ @Override
+ protected OutputStream doGetOutputStream(final boolean bAppend) throws Exception
+ {
+ // TODO - Don't write the entire file into memory. Use the stream-based
+ // methods on ChannelSftp once the work properly
+ /*
+ final ChannelSftp channel = getAbstractFileSystem().getChannel();
+ return new SftpOutputStream(channel);
+ */
+
+ final ChannelSftp channel = getAbstractFileSystem().getChannel();
+ return new SftpOutputStream(channel, channel.put(relPath));
+ }
+
+ /**
+ * An InputStream that monitors for end-of-file.
+ */
+ private class SftpInputStream extends MonitorInputStream
+ {
+ private final ChannelSftp channel;
+
+ public SftpInputStream(final ChannelSftp channel, final InputStream in)
+ {
+ super(in);
+ this.channel = channel;
+ }
+
+ /**
+ * Called after the stream has been closed.
+ */
+ @Override
+ protected void onClose() throws IOException
+ {
+ getAbstractFileSystem().putChannel(channel);
+ }
+ }
+
+ /**
+ * An OutputStream that wraps an sftp OutputStream, and closes the channel
+ * when the stream is closed.
+ */
+ private class SftpOutputStream extends MonitorOutputStream
+ {
+ private final ChannelSftp channel;
+
+ public SftpOutputStream(final ChannelSftp channel, final OutputStream out)
+ {
+ super(out);
+ this.channel = channel;
+ }
+
+ /**
+ * Called after this stream is closed.
+ */
+ @Override
+ protected void onClose() throws IOException
+ {
+ getAbstractFileSystem().putChannel(channel);
+ }
+ }
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpFileProvider.java
new file mode 100644
index 0000000..27fbf23
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpFileProvider.java
@@ -0,0 +1,153 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.sftp;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemConfigBuilder;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.UserAuthenticationData;
+import org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider;
+import org.apache.commons.vfs2.provider.GenericFileName;
+import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
+
+import com.jcraft.jsch.Session;
+
+/**
+ * A provider for accessing files over SFTP.
+ */
+public class SftpFileProvider extends AbstractOriginatingFileProvider
+{
+ /** User Information. */
+ public static final String ATTR_USER_INFO = "UI";
+
+ /** Authentication types. */
+ public static final UserAuthenticationData.Type[] AUTHENTICATOR_TYPES =
+ new UserAuthenticationData.Type[]
+ {
+ UserAuthenticationData.USERNAME, UserAuthenticationData.PASSWORD
+ };
+
+ /** The provider's capabilities. */
+ protected static final Collection<Capability> capabilities =
+ Collections.unmodifiableCollection(Arrays.asList(new Capability[]
+ {
+ Capability.CREATE,
+ Capability.DELETE,
+ Capability.RENAME,
+ Capability.GET_TYPE,
+ Capability.LIST_CHILDREN,
+ Capability.READ_CONTENT,
+ Capability.URI,
+ Capability.WRITE_CONTENT,
+ Capability.GET_LAST_MODIFIED,
+ Capability.SET_LAST_MODIFIED_FILE,
+ Capability.RANDOM_ACCESS_READ
+ }));
+
+ // private JSch jSch = new JSch();
+
+ /**
+ * Constructs a new provider.
+ */
+ public SftpFileProvider()
+ {
+ super();
+ setFileNameParser(SftpFileNameParser.getInstance());
+ }
+
+ /**
+ * Creates a {@link FileSystem}.
+ */
+ @Override
+ protected FileSystem doCreateFileSystem(final FileName name, final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ // JSch jsch = createJSch(fileSystemOptions);
+
+ // Create the file system
+ final GenericFileName rootName = (GenericFileName) name;
+
+ Session session;
+ UserAuthenticationData authData = null;
+ try
+ {
+ authData = UserAuthenticatorUtils.authenticate(fileSystemOptions, AUTHENTICATOR_TYPES);
+
+ session = SftpClientFactory.createConnection(
+ rootName.getHostName(),
+ rootName.getPort(),
+ UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME,
+ UserAuthenticatorUtils.toChar(rootName.getUserName())),
+ UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD,
+ UserAuthenticatorUtils.toChar(rootName.getPassword())),
+ fileSystemOptions);
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("vfs.provider.sftp/connect.error",
+ name,
+ e);
+ }
+ finally
+ {
+ UserAuthenticatorUtils.cleanup(authData);
+ }
+
+ return new SftpFileSystem(rootName, session, fileSystemOptions);
+ }
+
+
+ /**
+ * Returns the JSch.
+ *
+ * @return Returns the jSch.
+ */
+ /*
+ private JSch getJSch()
+ {
+ return this.jSch;
+ }
+ */
+
+ /**
+ * Initializes the component.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public void init() throws FileSystemException
+ {
+ }
+
+ @Override
+ public FileSystemConfigBuilder getConfigBuilder()
+ {
+ return SftpFileSystemConfigBuilder.getInstance();
+ }
+
+ @Override
+ public Collection<Capability> getCapabilities()
+ {
+ return capabilities;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpFileSystem.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpFileSystem.java
new file mode 100644
index 0000000..4de3885
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpFileSystem.java
@@ -0,0 +1,349 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.sftp;
+
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.Collection;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.UserAuthenticationData;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileSystem;
+import org.apache.commons.vfs2.provider.GenericFileName;
+import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
+
+import com.jcraft.jsch.ChannelExec;
+import com.jcraft.jsch.ChannelSftp;
+import com.jcraft.jsch.JSchException;
+import com.jcraft.jsch.Session;
+import com.jcraft.jsch.SftpException;
+
+/**
+ * Represents the files on an SFTP server.
+ */
+public class SftpFileSystem
+ extends AbstractFileSystem
+{
+ private static final int SLEEP_MILLIS = 100;
+
+ private static final int EXEC_BUFFER_SIZE = 128;
+
+ private static final long LAST_MOD_TIME_ACCURACY = 1000L;
+
+ private Session session;
+
+ // private final JSch jSch;
+
+ private ChannelSftp idleChannel;
+
+ /**
+ * Cache for the user ID (-1 when not set)
+ */
+ private int uid = -1;
+
+ /**
+ * Cache for the user groups ids (null when not set)
+ */
+ private int[] groupsIds;
+
+ protected SftpFileSystem(final GenericFileName rootName,
+ final Session session,
+ final FileSystemOptions fileSystemOptions)
+ {
+ super(rootName, null, fileSystemOptions);
+ this.session = session;
+ }
+
+ @Override
+ protected void doCloseCommunicationLink()
+ {
+ if (idleChannel != null)
+ {
+ idleChannel.disconnect();
+ idleChannel = null;
+ }
+
+ if (session != null)
+ {
+ session.disconnect();
+ session = null;
+ }
+ }
+
+ /**
+ * Returns an SFTP channel to the server.
+ *
+ * @return new or reused channel, never null.
+ * @throws FileSystemException if a session cannot be created.
+ * @throws IOException if an I/O error is detected.
+ */
+ protected ChannelSftp getChannel() throws IOException
+ {
+ ensureSession();
+ try
+ {
+ // Use the pooled channel, or create a new one
+ final ChannelSftp channel;
+ if (idleChannel != null)
+ {
+ channel = idleChannel;
+ idleChannel = null;
+ }
+ else
+ {
+ channel = (ChannelSftp) session.openChannel("sftp");
+ channel.connect();
+ final Boolean userDirIsRoot =
+ SftpFileSystemConfigBuilder.getInstance().getUserDirIsRoot(getFileSystemOptions());
+ final String workingDirectory = getRootName().getPath();
+ if (workingDirectory != null && (userDirIsRoot == null || !userDirIsRoot.booleanValue()))
+ {
+ try
+ {
+ channel.cd(workingDirectory);
+ }
+ catch (final SftpException e)
+ {
+ throw new FileSystemException("vfs.provider.sftp/change-work-directory.error",
+ workingDirectory, e);
+ }
+ }
+ }
+
+ final String fileNameEncoding = SftpFileSystemConfigBuilder.getInstance().getFileNameEncoding(
+ getFileSystemOptions());
+
+ if (fileNameEncoding != null)
+ {
+ try
+ {
+ channel.setFilenameEncoding(fileNameEncoding);
+ }
+ catch (final SftpException e)
+ {
+ throw new FileSystemException("vfs.provider.sftp/filename-encoding.error", fileNameEncoding);
+ }
+ }
+ return channel;
+ }
+ catch (final JSchException e)
+ {
+ throw new FileSystemException("vfs.provider.sftp/connect.error", getRootName(), e);
+ }
+ }
+
+ /**
+ * Ensures that the session link is established.
+ *
+ * @throws FileSystemException if a session cannot be created.
+ */
+ private void ensureSession() throws FileSystemException
+ {
+ if (this.session == null || !this.session.isConnected())
+ {
+ doCloseCommunicationLink();
+
+ // channel closed. e.g. by freeUnusedResources, but now we need it again
+ Session session;
+ UserAuthenticationData authData = null;
+ try
+ {
+ final GenericFileName rootName = (GenericFileName) getRootName();
+
+ authData = UserAuthenticatorUtils.authenticate(getFileSystemOptions(),
+ SftpFileProvider.AUTHENTICATOR_TYPES);
+
+ session = SftpClientFactory.createConnection(
+ rootName.getHostName(),
+ rootName.getPort(),
+ UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME,
+ UserAuthenticatorUtils.toChar(rootName.getUserName())),
+ UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD,
+ UserAuthenticatorUtils.toChar(rootName.getPassword())),
+ getFileSystemOptions());
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("vfs.provider.sftp/connect.error", getRootName(), e);
+ }
+ finally
+ {
+ UserAuthenticatorUtils.cleanup(authData);
+ }
+ this.session = session;
+ }
+ }
+
+ /**
+ * Returns a channel to the pool.
+ *
+ * @param channel the used channel.
+ */
+ protected void putChannel(final ChannelSftp channel)
+ {
+ if (idleChannel == null)
+ {
+ // put back the channel only if it is still connected
+ if (channel.isConnected() && !channel.isClosed())
+ {
+ idleChannel = channel;
+ }
+ }
+ else
+ {
+ channel.disconnect();
+ }
+ }
+
+ /**
+ * Adds the capabilities of this file system.
+ */
+ @Override
+ protected void addCapabilities(final Collection<Capability> caps)
+ {
+ caps.addAll(SftpFileProvider.capabilities);
+ }
+
+ /**
+ * Creates a file object. This method is called only if the requested
+ * file is not cached.
+ */
+ @Override
+ protected FileObject createFile(final AbstractFileName name)
+ throws FileSystemException
+ {
+ return new SftpFileObject(name, this);
+ }
+
+ /**
+ * Last modification time is only an int and in seconds, thus can be off by 999.
+ *
+ * @return 1000
+ */
+ @Override
+ public double getLastModTimeAccuracy()
+ {
+ return LAST_MOD_TIME_ACCURACY;
+ }
+
+ /**
+ * Gets the (numeric) group IDs.
+ *
+ * @return the (numeric) group IDs.
+ * @throws JSchException If a problem occurs while retrieving the group IDs.
+ * @throws IOException if an I/O error is detected.
+ * @since 2.1
+ */
+ public int[] getGroupsIds() throws JSchException, IOException
+ {
+ if (groupsIds == null)
+ {
+ final StringBuilder output = new StringBuilder();
+ final int code = executeCommand("id -G", output);
+ if (code != 0)
+ {
+ throw new JSchException("Could not get the groups id of the current user (error code: " + code + ")");
+ }
+
+ // Retrieve the different groups
+ final String[] groups = output.toString().trim().split("\\s+");
+
+ final int[] groupsIds = new int[groups.length];
+ for (int i = 0; i < groups.length; i++)
+ {
+ groupsIds[i] = Integer.parseInt(groups[i]);
+ }
+
+ this.groupsIds = groupsIds;
+ }
+ return groupsIds;
+ }
+
+ /**
+ * Get the (numeric) group IDs.
+ *
+ * @return The numeric user ID
+ * @throws JSchException If a problem occurs while retrieving the group ID.
+ * @throws IOException if an I/O error is detected.
+ * @since 2.1
+ */
+ public int getUId() throws JSchException, IOException
+ {
+ if (uid < 0)
+ {
+ final StringBuilder output = new StringBuilder();
+ final int code = executeCommand("id -u", output);
+ if (code != 0)
+ {
+ throw new FileSystemException("Could not get the user id of the current user (error code: " + code
+ + ")");
+ }
+ uid = Integer.parseInt(output.toString().trim());
+ }
+ return uid;
+ }
+
+ /**
+ * Execute a command and returns the (standard) output through a StringBuilder.
+ *
+ * @param command The command
+ * @param output The output
+ * @return The exit code of the command
+ * @throws JSchException if a JSch error is detected.
+ * @throws FileSystemException if a session cannot be created.
+ * @throws IOException if an I/O error is detected.
+ */
+ private int executeCommand(final String command, final StringBuilder output) throws JSchException, IOException
+ {
+ ensureSession();
+ final ChannelExec channel = (ChannelExec) session.openChannel("exec");
+
+ channel.setCommand(command);
+ channel.setInputStream(null);
+ final InputStreamReader stream = new InputStreamReader(channel.getInputStream());
+ channel.setErrStream(System.err, true);
+ channel.connect();
+
+ // Read the stream
+ final char[] buffer = new char[EXEC_BUFFER_SIZE];
+ int read;
+ while ((read = stream.read(buffer, 0, buffer.length)) >= 0)
+ {
+ output.append(buffer, 0, read);
+ }
+ stream.close();
+
+ // Wait until the command finishes (should not be long since we read the output stream)
+ while (!channel.isClosed())
+ {
+ try
+ {
+ Thread.sleep(SLEEP_MILLIS);
+ }
+ catch (final Exception ee)
+ {
+ // TODO: swallow exception, really?
+ }
+ }
+ channel.disconnect();
+ return channel.getExitStatus();
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpFileSystemConfigBuilder.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpFileSystemConfigBuilder.java
new file mode 100644
index 0000000..af2c6cd
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpFileSystemConfigBuilder.java
@@ -0,0 +1,708 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.sftp;
+
+import java.io.File;
+import java.io.Serializable;
+
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemConfigBuilder;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+
+import com.jcraft.jsch.UserInfo;
+
+/**
+ * The config builder for various SFTP configuration options.
+ */
+public final class SftpFileSystemConfigBuilder extends FileSystemConfigBuilder
+{
+ /**
+ * Proxy type.
+ */
+ public static final class ProxyType implements Serializable, Comparable<ProxyType>
+ {
+ /**
+ * serialVersionUID format is YYYYMMDD for the date of the last binary change.
+ */
+ private static final long serialVersionUID = 20101208L;
+
+ private final String proxyType;
+
+ private ProxyType(final String proxyType)
+ {
+ this.proxyType = proxyType;
+ }
+
+ @Override
+ public int compareTo(final ProxyType pType)
+ {
+ return this.proxyType.compareTo(pType.proxyType);
+ }
+
+ @Override
+ public boolean equals(final Object obj)
+ {
+ if (this == obj)
+ {
+ return true;
+ }
+ if (obj == null || this.getClass() != obj.getClass())
+ {
+ return false;
+ }
+
+ final ProxyType pType = (ProxyType) obj;
+
+ if (this.proxyType != null ? !this.proxyType.equals(pType.proxyType) : pType.proxyType != null)
+ {
+ return false;
+ }
+
+ return true;
+ }
+
+ /**
+ * @return a hash code value for this object.
+ * @since 2.0
+ */
+ @Override
+ public int hashCode()
+ {
+ return this.proxyType.hashCode();
+ }
+ }
+
+ /** HTTP Proxy. */
+ public static final ProxyType PROXY_HTTP = new ProxyType("http");
+
+ /** SOCKS Proxy. */
+ public static final ProxyType PROXY_SOCKS5 = new ProxyType("socks");
+
+ /**
+ * Connects to the SFTP server through a remote host reached by SSH.
+ * <p>
+ * On this proxy host, a command
+ * (e.g. {@linkplain SftpStreamProxy#NETCAT_COMMAND}
+ * or {@linkplain SftpStreamProxy#NETCAT_COMMAND}) is run to forward
+ * input/output streams between the target host and the VFS host.
+ * <p>
+ * When used, the proxy username ({@linkplain #setProxyUser}) and
+ * hostname ({@linkplain #setProxyHost}) <b>must</b> be set.
+ * Optionnaly, the command ({@linkplain #setProxyCommand}),
+ * password ({@linkplain #setProxyPassword}) and connection options
+ * ({@linkplain #setProxyOptions}) can be set.
+ */
+ public static final ProxyType PROXY_STREAM = new ProxyType("stream");
+
+ private static final String _PREFIX = SftpFileSystemConfigBuilder.class.getName();
+ private static final SftpFileSystemConfigBuilder BUILDER = new SftpFileSystemConfigBuilder();
+ private static final String COMPRESSION = _PREFIX + "COMPRESSION";
+ private static final String HOST_KEY_CHECK_ASK = "ask";
+ private static final String HOST_KEY_CHECK_NO = "no";
+ private static final String HOST_KEY_CHECK_YES = "yes";
+ private static final String IDENTITIES = _PREFIX + ".IDENTITIES";
+ private static final String IDENTITY_REPOSITORY_FACTORY = _PREFIX + "IDENTITY_REPOSITORY_FACTORY";
+ private static final String KNOWN_HOSTS = _PREFIX + ".KNOWN_HOSTS";
+ private static final String PREFERRED_AUTHENTICATIONS = _PREFIX + ".PREFERRED_AUTHENTICATIONS";
+
+ private static final String PROXY_HOST = _PREFIX + ".PROXY_HOST";
+ private static final String PROXY_USER = _PREFIX + ".PROXY_USER";
+ private static final String PROXY_OPTIONS = _PREFIX + ".PROXY_OPTIONS";
+ private static final String PROXY_TYPE = _PREFIX + ".PROXY_TYPE";
+ private static final String PROXY_PORT = _PREFIX + ".PROXY_PORT";
+ private static final String PROXY_PASSWORD = _PREFIX + ".PROXY_PASSWORD";
+ private static final String PROXY_COMMAND = _PREFIX + ".PROXY_COMMAND";
+
+ private static final String STRICT_HOST_KEY_CHECKING = _PREFIX + ".STRICT_HOST_KEY_CHECKING";
+ private static final String TIMEOUT = _PREFIX + ".TIMEOUT";
+ private static final String USER_DIR_IS_ROOT = _PREFIX + ".USER_DIR_IS_ROOT";
+ private static final String ENCODING = _PREFIX + ".ENCODING";
+
+ private SftpFileSystemConfigBuilder()
+ {
+ super("sftp.");
+ }
+
+ /**
+ * Gets the singleton builder.
+ *
+ * @return the singleton builder.
+ */
+ public static SftpFileSystemConfigBuilder getInstance()
+ {
+ return BUILDER;
+ }
+
+ /**
+ * @param opts
+ * The FileSystem options.
+ * @return The names of the compression algorithms, comma-separated.
+ * @see #setCompression
+ */
+ public String getCompression(final FileSystemOptions opts)
+ {
+ return this.getString(opts, COMPRESSION);
+ }
+
+ @Override
+ protected Class<? extends FileSystem> getConfigClass()
+ {
+ return SftpFileSystem.class;
+ }
+
+ /**
+ * Gets the file name encoding.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @return the file name encoding
+ */
+ public String getFileNameEncoding(final FileSystemOptions opts)
+ {
+ return this.getString(opts, ENCODING);
+ }
+
+ /**
+ * Gets the identity files (your private key files).
+ * <p>
+ * We use java.io.File because JSch cannot deal with VFS FileObjects.
+ *
+ * @param opts The FileSystem options.
+ * @return the array of identity Files.
+ * @see #setIdentities
+ * @deprecated As of 2.1 use {@link #getIdentityInfo(FileSystemOptions)}
+ */
+ @Deprecated
+ public File[] getIdentities(final FileSystemOptions opts)
+ {
+ final IdentityInfo[] info = getIdentityInfo(opts);
+ if (info != null)
+ {
+ final File[] files = new File[info.length];
+ for (int i = 0; i < files.length; ++i)
+ {
+ files[i] = info[i].getPrivateKey();
+ }
+ return files;
+ }
+ return null;
+ }
+
+ /**
+ * Gets the identity info.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @return the array of identity info instances.
+ * @see #setIdentityInfo
+ */
+ public IdentityInfo[] getIdentityInfo(final FileSystemOptions opts)
+ {
+ return (IdentityInfo[]) this.getParam(opts, IDENTITIES);
+ }
+
+ /**
+ * Get the identity repository factory.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @return the IdentityRepositoryFactory
+ */
+ public IdentityRepositoryFactory getIdentityRepositoryFactory(final FileSystemOptions opts)
+ {
+ return (IdentityRepositoryFactory) this.getParam(opts, IDENTITY_REPOSITORY_FACTORY);
+ }
+
+ /**
+ * @param opts
+ * The FileSystem options.
+ * @return the known hosts File.
+ * @see #setKnownHosts
+ */
+ public File getKnownHosts(final FileSystemOptions opts)
+ {
+ return (File) this.getParam(opts, KNOWN_HOSTS);
+ }
+
+ /**
+ * Gets authentication order.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @return The authentication order.
+ * @since 2.0
+ */
+ public String getPreferredAuthentications(final FileSystemOptions opts)
+ {
+ return getString(opts, PREFERRED_AUTHENTICATIONS);
+ }
+
+ /**
+ * Gets the command that will be run on the proxy
+ * host when using a {@linkplain SftpStreamProxy}. The
+ * command defaults to {@linkplain SftpStreamProxy#NETCAT_COMMAND}.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @return proxyOptions
+ * @see SftpStreamProxy
+ * @see #setProxyOptions
+ * @since 2.1
+ */
+ public String getProxyCommand(final FileSystemOptions opts)
+ {
+ return this.getString(opts, PROXY_COMMAND, SftpStreamProxy.NETCAT_COMMAND);
+ }
+
+ /**
+ * Gets the proxy to use for the SFTP connection.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @return proxyHost
+ * @see #getProxyPort
+ * @see #setProxyHost
+ */
+ public String getProxyHost(final FileSystemOptions opts)
+ {
+ return this.getString(opts, PROXY_HOST);
+ }
+
+ /**
+ * Gets the proxy options that are used to connect
+ * to the proxy host.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @return proxyOptions
+ * @see SftpStreamProxy
+ * @see #setProxyOptions
+ * @since 2.1
+ */
+ public FileSystemOptions getProxyOptions(final FileSystemOptions opts)
+ {
+ return (FileSystemOptions) this.getParam(opts, PROXY_OPTIONS);
+ }
+
+ /**
+ * Gets the proxy password that are used to connect
+ * to the proxy host.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @return proxyOptions
+ * @see SftpStreamProxy
+ * @see #setProxyPassword
+ * @since 2.1
+ */
+ public String getProxyPassword(final FileSystemOptions opts)
+ {
+ return this.getString(opts, PROXY_PASSWORD);
+ }
+
+ /**
+ * Gets the proxy-port to use for the SFTP the connection.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @return proxyPort: the port number or 0 if it is not set
+ * @see #setProxyPort
+ * @see #getProxyHost
+ */
+ public int getProxyPort(final FileSystemOptions opts)
+ {
+ return this.getInteger(opts, PROXY_PORT, 0);
+ }
+
+ /**
+ * Gets the proxy type to use for the SFTP connection.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @return The ProxyType.
+ */
+ public ProxyType getProxyType(final FileSystemOptions opts)
+ {
+ return (ProxyType) this.getParam(opts, PROXY_TYPE);
+ }
+
+ /**
+ * Gets the user name for the proxy used for the SFTP connection.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @return proxyUser
+ * @see #setProxyUser
+ * @since 2.1
+ */
+ public String getProxyUser(final FileSystemOptions opts)
+ {
+ return this.getString(opts, PROXY_USER);
+ }
+
+ /**
+ * @param opts
+ * The FileSystem options.
+ * @return the option value The host key checking.
+ * @see #setStrictHostKeyChecking(FileSystemOptions, String)
+ */
+ public String getStrictHostKeyChecking(final FileSystemOptions opts)
+ {
+ return this.getString(opts, STRICT_HOST_KEY_CHECKING, HOST_KEY_CHECK_NO);
+ }
+
+ /**
+ * @param opts
+ * The FileSystem options.
+ * @return The timeout value in milliseconds.
+ * @see #setTimeout
+ */
+ public Integer getTimeout(final FileSystemOptions opts)
+ {
+ return this.getInteger(opts, TIMEOUT);
+ }
+
+ /**
+ * Returns {@link Boolean#TRUE} if VFS should treat the user directory as the root directory. Defaults to
+ * <code>Boolean.TRUE</code> if the method {@link #setUserDirIsRoot(FileSystemOptions, boolean)} has not been
+ * invoked.
+ *
+ * @param opts
+ * The FileSystemOptions.
+ * @return <code>Boolean.TRUE</code> if VFS treats the user directory as the root directory.
+ * @see #setUserDirIsRoot
+ */
+ public Boolean getUserDirIsRoot(final FileSystemOptions opts)
+ {
+ return this.getBoolean(opts, USER_DIR_IS_ROOT, Boolean.TRUE);
+ }
+
+ /**
+ * @param opts
+ * The FileSystem options.
+ * @return The UserInfo.
+ * @see #setUserInfo
+ */
+ public UserInfo getUserInfo(final FileSystemOptions opts)
+ {
+ return (UserInfo) this.getParam(opts, UserInfo.class.getName());
+ }
+
+ /**
+ * Configures the compression algorithms to use.
+ * <p>
+ * For example, use {@code "zlib,none"} to enable compression.
+ * <p>
+ * See the Jsch documentation (in particular the README file) for details.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @param compression
+ * The names of the compression algorithms, comma-separated.
+ * @throws FileSystemException
+ * if an error occurs.
+ */
+ public void setCompression(final FileSystemOptions opts, final String compression) throws FileSystemException
+ {
+ this.setParam(opts, COMPRESSION, compression);
+ }
+
+ /**
+ * Sets the file name encoding.
+ *
+ * @param opts The FileSystem options.
+ * @param fileNameEncoding The name of the encoding to use for file names.
+ */
+ public void setFileNameEncoding(final FileSystemOptions opts, final String fileNameEncoding)
+ {
+ this.setParam(opts, ENCODING, fileNameEncoding);
+ }
+
+ /**
+ * Sets the identity files (your private key files).
+ * <p>
+ * We use {@link java.io.File} because JSch cannot deal with VFS FileObjects.
+ *
+ * @param opts The FileSystem options.
+ * @param identityFiles An array of identity Files.
+ * @throws FileSystemException if an error occurs.
+ * @deprecated As of 2.1 use {@link #setIdentityInfo(FileSystemOptions, IdentityInfo...)}
+ */
+ @Deprecated
+ public void setIdentities(final FileSystemOptions opts, final File... identityFiles)
+ throws FileSystemException
+ {
+ IdentityInfo[] info = null;
+ if (identityFiles != null)
+ {
+ info = new IdentityInfo[identityFiles.length];
+ for (int i = 0; i < identityFiles.length; i++)
+ {
+ info[i] = new IdentityInfo(identityFiles[i]);
+ }
+ }
+ this.setParam(opts, IDENTITIES, info);
+ }
+
+ /**
+ * Sets the identity info (your private key files).
+ *
+ * @param opts
+ * The FileSystem options.
+ * @param identites
+ * An array of identity info.
+ * @throws FileSystemException
+ * if an error occurs.
+ * @since 2.1
+ */
+ public void setIdentityInfo(final FileSystemOptions opts, final IdentityInfo... identites)
+ throws FileSystemException
+ {
+ this.setParam(opts, IDENTITIES, identites);
+ }
+
+ /**
+ * Set the identity repository.
+ * <p>
+ * This is useful when you want to use e.g. an SSH agent as provided.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @param factory
+ * An identity repository.
+ * @throws FileSystemException
+ * if an error occurs.
+ * @see <a href="http://www.jcraft.com/jsch-agent-proxy/">JSch agent proxy</a>
+ */
+ public void setIdentityRepositoryFactory(final FileSystemOptions opts, final IdentityRepositoryFactory factory)
+ throws FileSystemException
+ {
+ this.setParam(opts, IDENTITY_REPOSITORY_FACTORY, factory);
+ }
+
+ /**
+ * Sets the known_hosts file. e.g. {@code /home/user/.ssh/known_hosts2}.
+ * <p>
+ * We use {@link java.io.File} because JSch cannot deal with VFS FileObjects.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @param knownHosts
+ * The known hosts file.
+ * @throws FileSystemException
+ * if an error occurs.
+ */
+ public void setKnownHosts(final FileSystemOptions opts, final File knownHosts) throws FileSystemException
+ {
+ this.setParam(opts, KNOWN_HOSTS, knownHosts);
+ }
+
+ /**
+ * Configures authentication order.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @param preferredAuthentications
+ * The authentication order.
+ * @since 2.0
+ */
+ public void setPreferredAuthentications(final FileSystemOptions opts, final String preferredAuthentications)
+ {
+ this.setParam(opts, PREFERRED_AUTHENTICATIONS, preferredAuthentications);
+ }
+
+ /**
+ * Sets the proxy username to use for the SFTP connection.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @param proxyCommand
+ * the port
+ * @see #getProxyOptions
+ * @since 2.1
+ */
+ public void setProxyCommand(final FileSystemOptions opts, final String proxyCommand)
+ {
+ this.setParam(opts, PROXY_COMMAND, proxyCommand);
+ }
+
+ /**
+ * Sets the proxy to use for the SFTP connection.
+ *
+ * You MUST also set the proxy port to use the proxy.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @param proxyHost
+ * the host
+ * @see #setProxyPort
+ */
+ public void setProxyHost(final FileSystemOptions opts, final String proxyHost)
+ {
+ this.setParam(opts, PROXY_HOST, proxyHost);
+ }
+
+ /**
+ * Sets the proxy username to use for the SFTP connection.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @param proxyOptions
+ * the options
+ * @see #getProxyOptions
+ * @since 2.1
+ */
+ public void setProxyOptions(final FileSystemOptions opts, final FileSystemOptions proxyOptions)
+ {
+ this.setParam(opts, PROXY_OPTIONS, proxyOptions);
+ }
+
+ /**
+ * Sets the proxy password to use for the SFTP connection.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @param proxyPassword
+ * the username used to connect to the proxy
+ * @see #getProxyPassword
+ * @since 2.1
+ */
+ public void setProxyPassword(final FileSystemOptions opts, final String proxyPassword)
+ {
+ this.setParam(opts, PROXY_PASSWORD, proxyPassword);
+ }
+
+ /**
+ * Sets the proxy port to use for the SFTP connection.
+ * <p>
+ * You MUST also set the proxy host to use the proxy.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @param proxyPort
+ * the port
+ * @see #setProxyHost
+ */
+ public void setProxyPort(final FileSystemOptions opts, final int proxyPort)
+ {
+ this.setParam(opts, PROXY_PORT, Integer.valueOf(proxyPort));
+ }
+
+ /**
+ * Sets the proxy type to use for the SFTP connection.
+ *
+ * The possibles values are:
+ * <ul>
+ * <li>{@linkplain #PROXY_HTTP} connects using an HTTP proxy</li>
+ * <li>{@linkplain #PROXY_SOCKS5} connects using an Socket5 proxy</li>
+ * <li>{@linkplain #PROXY_STREAM} connects through a remote host stream command</li>
+ * </ul>
+ *
+ * @param opts
+ * The FileSystem options.
+ * @param proxyType
+ * the type of the proxy to use.
+ */
+ public void setProxyType(final FileSystemOptions opts, final ProxyType proxyType)
+ {
+ this.setParam(opts, PROXY_TYPE, proxyType);
+ }
+
+ /**
+ * Sets the proxy username to use for the SFTP connection.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @param proxyUser
+ * the username used to connect to the proxy
+ * @see #getProxyUser
+ * @since 2.1
+ */
+ public void setProxyUser(final FileSystemOptions opts, final String proxyUser)
+ {
+ this.setParam(opts, PROXY_USER, proxyUser);
+ }
+
+ /**
+ * Configures the host key checking to use.
+ * <p>
+ * Valid arguments are: {@code "yes"}, {@code "no"} and {@code "ask"}.
+ * </p>
+ * <p>
+ * See the jsch documentation for details.
+ * </p>
+ *
+ * @param opts
+ * The FileSystem options.
+ * @param hostKeyChecking
+ * The host key checking to use.
+ * @throws FileSystemException
+ * if an error occurs.
+ */
+ public void setStrictHostKeyChecking(final FileSystemOptions opts, final String hostKeyChecking)
+ throws FileSystemException
+ {
+ if (hostKeyChecking == null
+ || (!hostKeyChecking.equals(HOST_KEY_CHECK_ASK) && !hostKeyChecking.equals(HOST_KEY_CHECK_NO) &&
+ !hostKeyChecking.equals(HOST_KEY_CHECK_YES)))
+ {
+ throw new FileSystemException("vfs.provider.sftp/StrictHostKeyChecking-arg.error", hostKeyChecking);
+ }
+
+ this.setParam(opts, STRICT_HOST_KEY_CHECKING, hostKeyChecking);
+ }
+
+ /**
+ * Sets the timeout value on Jsch session.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @param timeout
+ * The timeout in milliseconds.
+ */
+ public void setTimeout(final FileSystemOptions opts, final Integer timeout)
+ {
+ this.setParam(opts, TIMEOUT, timeout);
+ }
+
+ /**
+ * Sets the whether to use the user directory as root (do not change to file system root).
+ *
+ * @param opts
+ * The FileSystem options.
+ * @param userDirIsRoot
+ * true if the user directory is the root directory.
+ */
+ public void setUserDirIsRoot(final FileSystemOptions opts, final boolean userDirIsRoot)
+ {
+ this.setParam(opts, USER_DIR_IS_ROOT, userDirIsRoot ? Boolean.TRUE : Boolean.FALSE);
+ }
+
+ /**
+ * Sets the Jsch UserInfo class to use.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @param info
+ * User information.
+ */
+ public void setUserInfo(final FileSystemOptions opts, final UserInfo info)
+ {
+ this.setParam(opts, UserInfo.class.getName(), info);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpRandomAccessContent.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpRandomAccessContent.java
new file mode 100644
index 0000000..30d6e2e
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpRandomAccessContent.java
@@ -0,0 +1,153 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.sftp;
+
+import java.io.DataInputStream;
+import java.io.FilterInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.provider.AbstractRandomAccessStreamContent;
+import org.apache.commons.vfs2.util.RandomAccessMode;
+
+/**
+ * Random access content.
+ */
+class SftpRandomAccessContent extends AbstractRandomAccessStreamContent
+{
+ /** file pointer */
+ protected long filePointer = 0;
+
+ private final SftpFileObject fileObject;
+ private DataInputStream dis = null;
+ private InputStream mis = null;
+
+ SftpRandomAccessContent(final SftpFileObject fileObject, final RandomAccessMode mode)
+ {
+ super(mode);
+
+ this.fileObject = fileObject;
+ // fileSystem = (FtpFileSystem) this.fileObject.getFileSystem();
+ }
+
+ @Override
+ public long getFilePointer() throws IOException
+ {
+ return filePointer;
+ }
+
+ @Override
+ public void seek(final long pos) throws IOException
+ {
+ if (pos == filePointer)
+ {
+ // no change
+ return;
+ }
+
+ if (pos < 0)
+ {
+ throw new FileSystemException("vfs.provider/random-access-invalid-position.error",
+ Long.valueOf(pos));
+ }
+ if (dis != null)
+ {
+ close();
+ }
+
+ filePointer = pos;
+ }
+
+ @Override
+ protected DataInputStream getDataInputStream() throws IOException
+ {
+ if (dis != null)
+ {
+ return dis;
+ }
+
+ // FtpClient client = fileSystem.getClient();
+ mis = fileObject.getInputStream(filePointer);
+ dis = new DataInputStream(new FilterInputStream(mis)
+ {
+ @Override
+ public int read() throws IOException
+ {
+ final int ret = super.read();
+ if (ret > -1)
+ {
+ filePointer++;
+ }
+ return ret;
+ }
+
+ @Override
+ public int read(final byte[] b) throws IOException
+ {
+ final int ret = super.read(b);
+ if (ret > -1)
+ {
+ filePointer += ret;
+ }
+ return ret;
+ }
+
+ @Override
+ public int read(final byte[] b, final int off, final int len) throws IOException
+ {
+ final int ret = super.read(b, off, len);
+ if (ret > -1)
+ {
+ filePointer += ret;
+ }
+ return ret;
+ }
+
+ @Override
+ public void close() throws IOException
+ {
+ SftpRandomAccessContent.this.close();
+ }
+ });
+
+ return dis;
+ }
+
+
+ @Override
+ public void close() throws IOException
+ {
+ if (dis != null)
+ {
+ // mis.abort();
+ mis.close();
+
+ // this is to avoid recursive close
+ final DataInputStream oldDis = dis;
+ dis = null;
+ oldDis.close();
+ mis = null;
+ }
+ }
+
+ @Override
+ public long length() throws IOException
+ {
+ return fileObject.getContent().getSize();
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpStreamProxy.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpStreamProxy.java
new file mode 100644
index 0000000..c595b14
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpStreamProxy.java
@@ -0,0 +1,185 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.commons.vfs2.provider.sftp;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.Socket;
+
+import org.apache.commons.vfs2.FileSystemOptions;
+
+import com.jcraft.jsch.ChannelExec;
+import com.jcraft.jsch.Proxy;
+import com.jcraft.jsch.Session;
+import com.jcraft.jsch.SocketFactory;
+
+/**
+ * Stream based proxy for JSch.
+ *
+ * <p>
+ * Use a command on the proxy that will forward the SSH stream to the target host and port.
+ * </p>
+ *
+ * @since 2.1
+ */
+public class SftpStreamProxy implements Proxy
+{
+ /**
+ * Command format using bash built-in TCP stream.
+ */
+ public static final String BASH_TCP_COMMAND = "/bin/bash -c 'exec 3<>/dev/tcp/%s/%d; cat <&3 & cat >&3; kill $!";
+
+ /**
+ * Command format using netcat command.
+ */
+ public static final String NETCAT_COMMAND = "nc -q 0 %s %d";
+
+ private ChannelExec channel;
+
+ /**
+ * Command pattern to execute on the proxy host.
+ * <p>
+ * When run, the command output should be forwarded to the target host and port, and its input should be forwarded
+ * from the target host and port.
+ * <p>
+ * The command will be created for each host/port pair by using {@linkplain String#format(String, Object...)} with
+ * two objects: the target host name ({@linkplain String}) and the target port ({@linkplain Integer}).
+ * <p>
+ * Here are two examples (that can be easily used by using the static members of this class):
+ * <ul>
+ * <li><code>nc -q 0 %s %d</code> to use the netcat command ({@linkplain #NETCAT_COMMAND})</li>
+ * <li><code>/bin/bash -c 'exec 3<>/dev/tcp/%s/%d; cat <&3 & cat >&3; kill $!</code> will use bash built-in TCP
+ * stream, which can be useful when there is no netcat available. ({@linkplain #BASH_TCP_COMMAND})</li>
+ * </ul>
+ */
+ private final String commandFormat;
+
+ /**
+ * Hostname used to connect to the proxy host.
+ */
+ private final String proxyHost;
+
+ /**
+ * The options for connection.
+ */
+ private final FileSystemOptions proxyOptions;
+
+ /**
+ * The password to be used for connection.
+ */
+ private final String proxyPassword;
+
+ /**
+ * Port used to connect to the proxy host.
+ */
+ private final int proxyPort;
+
+ /**
+ * Username used to connect to the proxy host.
+ */
+ private final String proxyUser;
+
+ private Session session;
+
+ /**
+ * Creates a stream proxy.
+ *
+ * @param commandFormat
+ * A format string that will be used to create the command to execute on the proxy host using
+ * {@linkplain String#format(String, Object...)}. Two parameters are given to the format command, the
+ * target host name (String) and port (Integer).
+ * @param proxyUser
+ * The proxy user
+ * @param proxyPassword
+ * The proxy password
+ * @param proxyHost
+ * The proxy host
+ * @param proxyPort
+ * The port to connect to on the proxy
+ * @param proxyOptions
+ * Options used when connecting to the proxy
+ */
+ public SftpStreamProxy(final String commandFormat, final String proxyUser, final String proxyHost,
+ final int proxyPort, final String proxyPassword, final FileSystemOptions proxyOptions)
+ {
+ this.proxyHost = proxyHost;
+ this.proxyPort = proxyPort;
+ this.proxyUser = proxyUser;
+ this.proxyPassword = proxyPassword;
+ this.commandFormat = commandFormat;
+ this.proxyOptions = proxyOptions;
+ }
+
+ @Override
+ public void close()
+ {
+ if (channel != null)
+ {
+ channel.disconnect();
+ }
+ if (session != null)
+ {
+ session.disconnect();
+ }
+ }
+
+ @Override
+ public void connect(final SocketFactory socketFactory, final String targetHost,
+ final int targetPort, final int timeout)
+ throws Exception
+ {
+ session = SftpClientFactory.createConnection(proxyHost, proxyPort, proxyUser.toCharArray(),
+ proxyPassword.toCharArray(), proxyOptions);
+ channel = (ChannelExec) session.openChannel("exec");
+ channel.setCommand(String.format(commandFormat, targetHost, targetPort));
+ channel.connect(timeout);
+ }
+
+ @Override
+ public InputStream getInputStream()
+ {
+ try
+ {
+ return channel.getInputStream();
+ }
+ catch (final IOException e)
+ {
+ throw new IllegalStateException("IOException getting the SSH proxy input stream", e);
+ }
+ }
+
+ @Override
+ public OutputStream getOutputStream()
+ {
+ try
+ {
+ return channel.getOutputStream();
+ }
+ catch (final IOException e)
+ {
+ throw new IllegalStateException("IOException getting the SSH proxy output stream", e);
+ }
+ }
+
+ @Override
+ public Socket getSocket()
+ {
+ return null;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/TrustEveryoneUserInfo.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/TrustEveryoneUserInfo.java
new file mode 100644
index 0000000..d8ef515
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/TrustEveryoneUserInfo.java
@@ -0,0 +1,71 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.sftp;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+import com.jcraft.jsch.UserInfo;
+
+/**
+ * Helper class to trust a new host.
+ */
+public class TrustEveryoneUserInfo implements UserInfo
+{
+ private static final Log log = LogFactory.getLog(TrustEveryoneUserInfo.class);
+
+ @Override
+ public String getPassphrase()
+ {
+ return null;
+ }
+
+ @Override
+ public String getPassword()
+ {
+ return null;
+ }
+
+ @Override
+ public boolean promptPassword(final String s)
+ {
+ log.info(s + " - Answer: False");
+ return false;
+ }
+
+ @Override
+ public boolean promptPassphrase(final String s)
+ {
+ log.info(s + " - Answer: False");
+ return false;
+ }
+
+ @Override
+ public boolean promptYesNo(final String s)
+ {
+ log.debug(s + " - Answer: Yes");
+
+ // trust
+ return true;
+ }
+
+ @Override
+ public void showMessage(final String s)
+ {
+ log.debug(s);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/package.html
new file mode 100644
index 0000000..e33b51b
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/sftp/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>The SFTP Provider.</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/tar/TarFileObject.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/tar/TarFileObject.java
new file mode 100644
index 0000000..7d8d0f6
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/tar/TarFileObject.java
@@ -0,0 +1,174 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.tar;
+
+import java.io.InputStream;
+import java.util.HashSet;
+
+import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileObject;
+
+/**
+ * A file in a Tar file system.
+ */
+public class TarFileObject extends AbstractFileObject<TarFileSystem>
+{
+ /** The TarArchiveEntry */
+ private TarArchiveEntry entry;
+ private final HashSet<String> children = new HashSet<String>();
+ private FileType type;
+
+ protected TarFileObject(final AbstractFileName name,
+ final TarArchiveEntry entry,
+ final TarFileSystem fs,
+ final boolean tarExists) throws FileSystemException
+ {
+ super(name, fs);
+ setTarEntry(entry);
+ if (!tarExists)
+ {
+ type = FileType.IMAGINARY;
+ }
+ }
+
+ /**
+ * Sets the details for this file object.
+ */
+ void setTarEntry(final TarArchiveEntry entry)
+ {
+ if (this.entry != null)
+ {
+ return;
+ }
+
+ if (entry == null || entry.isDirectory())
+ {
+ type = FileType.FOLDER;
+ }
+ else
+ {
+ type = FileType.FILE;
+ }
+
+ this.entry = entry;
+ }
+
+ /**
+ * Attaches a child.
+ * @param childName Name of child to remember.
+ */
+ protected void attachChild(final FileName childName)
+ {
+ children.add(childName.getBaseName());
+ }
+
+ /**
+ * Determines if this file can be written to.
+ *
+ * @return {@code true} if this file is writeable, {@code false} if not.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public boolean isWriteable() throws FileSystemException
+ {
+ return false;
+ }
+
+ /**
+ * Returns the file's type.
+ */
+ @Override
+ protected FileType doGetType()
+ {
+ return type;
+ }
+
+ /**
+ * Lists the children of the file.
+ */
+ @Override
+ protected String[] doListChildren()
+ {
+ try
+ {
+ if (!getType().hasChildren())
+ {
+ return null;
+ }
+ }
+ catch (final FileSystemException e)
+ {
+ // should not happen as the type has already been cached.
+ throw new RuntimeException(e);
+ }
+
+ return children.toArray(new String[children.size()]);
+ }
+
+ /**
+ * Returns the size of the file content (in bytes). Is only called if
+ * {@link #doGetType} returns {@link FileType#FILE}.
+ */
+ @Override
+ protected long doGetContentSize()
+ {
+ if (entry == null)
+ {
+ return 0;
+ }
+
+ return entry.getSize();
+ }
+
+ /**
+ * Returns the last modified time of this file.
+ */
+ @Override
+ protected long doGetLastModifiedTime() throws Exception
+ {
+ if (entry == null)
+ {
+ return 0;
+ }
+
+ return entry.getModTime().getTime();
+ }
+
+ /**
+ * Creates an input stream to read the file content from. Is only called
+ * if {@link #doGetType} returns {@link FileType#FILE}. The input stream
+ * returned by this method is guaranteed to be closed before this
+ * method is called again.
+ */
+ @Override
+ protected InputStream doGetInputStream() throws Exception
+ {
+ // VFS-210: zip allows to gather an input stream even from a directory and will
+ // return -1 on the first read. getType should not be expensive and keeps the tests
+ // running
+ if (!getType().hasContent())
+ {
+ throw new FileSystemException("vfs.provider/read-not-file.error", getName());
+ }
+
+ return getAbstractFileSystem().getInputStream(entry);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/tar/TarFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/tar/TarFileProvider.java
new file mode 100644
index 0000000..63a4ef0
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/tar/TarFileProvider.java
@@ -0,0 +1,81 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.tar;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractLayeredFileProvider;
+import org.apache.commons.vfs2.provider.FileProvider;
+import org.apache.commons.vfs2.provider.LayeredFileName;
+
+/**
+ * A file system provider for Tar files. Provides read-only file systems.
+ */
+public class TarFileProvider extends AbstractLayeredFileProvider implements FileProvider
+{
+ /** The provider's capabilities */
+ protected static final Collection<Capability> capabilities =
+ Collections.unmodifiableCollection(Arrays.asList(new Capability[]
+ {
+ Capability.GET_LAST_MODIFIED,
+ Capability.GET_TYPE,
+ Capability.LIST_CHILDREN,
+ Capability.READ_CONTENT,
+ Capability.URI,
+ Capability.VIRTUAL
+ }));
+
+ public TarFileProvider()
+ {
+ super();
+ }
+
+ /**
+ * Creates a layered file system. This method is called if the file system
+ * is not cached.
+ *
+ * @param scheme The URI scheme.
+ * @param file The file to create the file system on top of.
+ * @return The file system.
+ */
+ @Override
+ protected FileSystem doCreateFileSystem(final String scheme,
+ final FileObject file,
+ final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ final AbstractFileName rootName =
+ new LayeredFileName(scheme, file.getName(), FileName.ROOT_PATH, FileType.FOLDER);
+ return new TarFileSystem(rootName, file, fileSystemOptions);
+ }
+
+ @Override
+ public Collection<Capability> getCapabilities()
+ {
+ return capabilities;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/tar/TarFileSystem.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/tar/TarFileSystem.java
new file mode 100644
index 0000000..bc783e5
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/tar/TarFileSystem.java
@@ -0,0 +1,264 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.tar;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.zip.GZIPInputStream;
+
+import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
+import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.Selectors;
+import org.apache.commons.vfs2.VfsLog;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileSystem;
+import org.apache.commons.vfs2.provider.UriParser;
+import org.apache.commons.vfs2.provider.bzip2.Bzip2FileObject;
+
+/**
+ * A read-only file system for Tar files.
+ */
+public class TarFileSystem extends AbstractFileSystem
+{
+ private static final int DEFAULT_INDEX_SIZE = 100;
+
+ private static final Log LOG = LogFactory.getLog(TarFileSystem.class);
+
+ private final File file;
+ private TarArchiveInputStream tarFile;
+
+ protected TarFileSystem(final AbstractFileName rootName,
+ final FileObject parentLayer,
+ final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ super(rootName, parentLayer, fileSystemOptions);
+
+ // Make a local copy of the file
+ file = parentLayer.getFileSystem().replicateFile(parentLayer, Selectors.SELECT_SELF);
+
+ // Open the Tar file
+ if (!file.exists())
+ {
+ // Don't need to do anything
+ tarFile = null;
+ return;
+ }
+
+ // tarFile = createTarFile(this.file);
+ }
+
+ @Override
+ public void init() throws FileSystemException
+ {
+ super.init();
+
+ // Build the index
+ try
+ {
+ final List<TarFileObject> strongRef = new ArrayList<TarFileObject>(DEFAULT_INDEX_SIZE);
+ TarArchiveEntry entry;
+ while ((entry = getTarFile().getNextTarEntry()) != null)
+ {
+ final AbstractFileName name = (AbstractFileName) getFileSystemManager().resolveName(getRootName(),
+ UriParser.encode(entry.getName()));
+
+ // Create the file
+ TarFileObject fileObj;
+ if (entry.isDirectory() && getFileFromCache(name) != null)
+ {
+ fileObj = (TarFileObject) getFileFromCache(name);
+ fileObj.setTarEntry(entry);
+ continue;
+ }
+
+ fileObj = createTarFileObject(name, entry);
+ putFileToCache(fileObj);
+ strongRef.add(fileObj);
+ fileObj.holdObject(strongRef);
+
+ // Make sure all ancestors exist
+ // TODO - create these on demand
+ TarFileObject parent = null;
+ for (AbstractFileName parentName = (AbstractFileName) name.getParent();
+ parentName != null;
+ fileObj = parent, parentName = (AbstractFileName) parentName.getParent())
+ {
+ // Locate the parent
+ parent = (TarFileObject) getFileFromCache(parentName);
+ if (parent == null)
+ {
+ parent = createTarFileObject(parentName, null);
+ putFileToCache(parent);
+ strongRef.add(parent);
+ parent.holdObject(strongRef);
+ }
+
+ // Attach child to parent
+ parent.attachChild(fileObj.getName());
+ }
+ }
+ }
+ catch (final IOException e)
+ {
+ throw new FileSystemException(e);
+ }
+ finally
+ {
+ closeCommunicationLink();
+ }
+ }
+
+ public InputStream getInputStream(final TarArchiveEntry entry) throws FileSystemException
+ {
+ resetTarFile();
+ try
+ {
+ while (!tarFile.getNextEntry().equals(entry))
+ {
+ }
+ return tarFile;
+ }
+ catch (final IOException e)
+ {
+ throw new FileSystemException(e);
+ }
+ }
+
+ protected void resetTarFile() throws FileSystemException
+ {
+ // Reading specific entries requires skipping through the tar file from the beginning
+ // Not especially elegant, but we don't have the ability to seek to specific positions
+ // with an input stream.
+ if (this.file.exists())
+ {
+ recreateTarFile();
+ }
+ }
+
+ private void recreateTarFile() throws FileSystemException
+ {
+ if (this.tarFile != null)
+ {
+ try
+ {
+ this.tarFile.close();
+ }
+ catch (final IOException e)
+ {
+ throw new FileSystemException("vfs.provider.tar/close-tar-file.error", file, e);
+ }
+ tarFile = null;
+ }
+ final TarArchiveInputStream tarFile = createTarFile(this.file);
+ this.tarFile = tarFile;
+ }
+
+ protected TarArchiveInputStream getTarFile() throws FileSystemException
+ {
+ if (tarFile == null && this.file.exists())
+ {
+ recreateTarFile();
+ }
+
+ return tarFile;
+ }
+
+ protected TarFileObject createTarFileObject(final AbstractFileName name,
+ final TarArchiveEntry entry) throws FileSystemException
+ {
+ return new TarFileObject(name, entry, this, true);
+ }
+
+ protected TarArchiveInputStream createTarFile(final File file) throws FileSystemException
+ {
+ try
+ {
+ if ("tgz".equalsIgnoreCase(getRootName().getScheme()))
+ {
+ return new TarArchiveInputStream(new GZIPInputStream(new FileInputStream(file)));
+ }
+ else if ("tbz2".equalsIgnoreCase(getRootName().getScheme()))
+ {
+ return new TarArchiveInputStream(Bzip2FileObject.wrapInputStream(file.getAbsolutePath(),
+ new FileInputStream(file)));
+ }
+ return new TarArchiveInputStream(new FileInputStream(file));
+ }
+ catch (final IOException ioe)
+ {
+ throw new FileSystemException("vfs.provider.tar/open-tar-file.error", file, ioe);
+ }
+ }
+
+ @Override
+ protected void doCloseCommunicationLink()
+ {
+ // Release the tar file
+ try
+ {
+ if (tarFile != null)
+ {
+ tarFile.close();
+ tarFile = null;
+ }
+ }
+ catch (final IOException e)
+ {
+ // getLogger().warn("vfs.provider.tar/close-tar-file.error :" + file, e);
+ VfsLog.warn(getLogger(), LOG, "vfs.provider.tar/close-tar-file.error :" + file, e);
+ }
+ }
+
+ /**
+ * Returns the capabilities of this file system.
+ */
+ @Override
+ protected void addCapabilities(final Collection<Capability> caps)
+ {
+ caps.addAll(TarFileProvider.capabilities);
+ }
+
+ /**
+ * Creates a file object.
+ */
+ @Override
+ protected FileObject createFile(final AbstractFileName name) throws FileSystemException
+ {
+ // This is only called for files which do not exist in the Tar file
+ return new TarFileObject(name, null, this, false);
+ }
+
+ /**
+ * will be called after all file-objects closed their streams.
+ protected void notifyAllStreamsClosed()
+ {
+ closeCommunicationLink();
+ }
+ */
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/tar/Tbz2FileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/tar/Tbz2FileProvider.java
new file mode 100644
index 0000000..e31884f
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/tar/Tbz2FileProvider.java
@@ -0,0 +1,54 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.tar;
+
+import java.util.Collection;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.provider.CompositeFileProvider;
+
+/**
+ * A file system provider for Tar files. Provides read-only file systems.
+ */
+public class Tbz2FileProvider extends CompositeFileProvider
+{
+ /** The provider's capabilities */
+ protected static final Collection<Capability> capabilities = TarFileProvider.capabilities;
+
+ private static final String[] SCHEMES = new String[]
+ {
+ "bz2",
+ "tar"
+ };
+
+ public Tbz2FileProvider()
+ {
+ super();
+ }
+
+ @Override
+ protected String[] getSchemes()
+ {
+ return SCHEMES;
+ }
+
+ @Override
+ public Collection<Capability> getCapabilities()
+ {
+ return capabilities;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/tar/TgzFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/tar/TgzFileProvider.java
new file mode 100644
index 0000000..b63bfcb
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/tar/TgzFileProvider.java
@@ -0,0 +1,54 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.tar;
+
+import java.util.Collection;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.provider.CompositeFileProvider;
+
+/**
+ * A file system provider for Tar files. Provides read-only file systems.
+ */
+public class TgzFileProvider extends CompositeFileProvider
+{
+ /** The provider's capabilities */
+ protected static final Collection<Capability> capabilities = TarFileProvider.capabilities;
+
+ private static final String[] SCHEMES = new String[]
+ {
+ "gz",
+ "tar"
+ };
+
+ public TgzFileProvider()
+ {
+ super();
+ }
+
+ @Override
+ protected String[] getSchemes()
+ {
+ return SCHEMES;
+ }
+
+ @Override
+ public Collection<Capability> getCapabilities()
+ {
+ return capabilities;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/tar/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/tar/package.html
new file mode 100644
index 0000000..a70bf44
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/tar/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>The Tar File Provider.</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/temp/TemporaryFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/temp/TemporaryFileProvider.java
new file mode 100644
index 0000000..4dda935
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/temp/TemporaryFileProvider.java
@@ -0,0 +1,132 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.temp;
+
+import java.io.File;
+import java.util.Collection;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.AbstractFileProvider;
+import org.apache.commons.vfs2.provider.FileProvider;
+import org.apache.commons.vfs2.provider.UriParser;
+import org.apache.commons.vfs2.provider.local.DefaultLocalFileProvider;
+import org.apache.commons.vfs2.provider.local.LocalFileSystem;
+
+/**
+ * A provider for temporary files.
+ */
+public class TemporaryFileProvider
+ extends AbstractFileProvider
+ implements FileProvider, Comparable<Object>
+{
+ private File rootFile;
+
+ /*
+ private final static FileName tmpFileName = new AbstractFileName("tmp", "/")
+ {
+ protected FileName createName(String absPath)
+ {
+ return null;
+ }
+
+ protected void appendRootUri(StringBuffer buffer)
+ {
+ }
+ };
+*/
+
+ public TemporaryFileProvider(final File rootFile)
+ {
+ this();
+
+ this.rootFile = rootFile;
+ }
+
+ public TemporaryFileProvider()
+ {
+ super();
+ }
+
+ @Override
+ public int compareTo(final Object o)
+ {
+ final int h1 = hashCode();
+ final int h2 = o.hashCode();
+ if (h1 < h2)
+ {
+ return -1;
+ }
+ if (h1 > h2)
+ {
+ return 1;
+ }
+
+ return 0;
+ }
+
+ /**
+ * Locates a file object, by absolute URI.
+ * @param baseFile The base FileObject.
+ * @param uri The URI of the file to be located.
+ * @param properties FileSystemOptions to use to locate or create the file.
+ * @return The FileObject.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public synchronized FileObject findFile(final FileObject baseFile, final String uri,
+ final FileSystemOptions properties)
+ throws FileSystemException
+ {
+ // Parse the name
+ final StringBuilder buffer = new StringBuilder(uri);
+ final String scheme = UriParser.extractScheme(uri, buffer);
+ UriParser.fixSeparators(buffer);
+ UriParser.normalisePath(buffer);
+ final String path = buffer.toString();
+
+ // Create the temp file system if it does not exist
+ // FileSystem filesystem = findFileSystem( this, (Properties) null);
+ FileSystem filesystem = findFileSystem(this, properties);
+ if (filesystem == null)
+ {
+ if (rootFile == null)
+ {
+ rootFile = getContext().getTemporaryFileStore().allocateFile("tempfs");
+ }
+ final FileName rootName =
+ getContext().parseURI(scheme + ":" + FileName.ROOT_PATH);
+ // final FileName rootName =
+ // new LocalFileName(scheme, scheme + ":", FileName.ROOT_PATH);
+ filesystem = new LocalFileSystem(rootName, rootFile.getAbsolutePath(), properties);
+ addFileSystem(this, filesystem);
+ }
+
+ // Find the file
+ return filesystem.resolveFile(path);
+ }
+
+ @Override
+ public Collection<Capability> getCapabilities()
+ {
+ return DefaultLocalFileProvider.capabilities;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/temp/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/temp/package.html
new file mode 100644
index 0000000..4b027ea
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/temp/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>The Temporary Filespace Provider.</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/url/UrlFileName.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/url/UrlFileName.java
new file mode 100644
index 0000000..01684be
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/url/UrlFileName.java
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.url;
+
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.provider.URLFileName;
+
+/**
+ * A URL FileName.
+ */
+public class UrlFileName extends URLFileName
+{
+ /**
+ * The constructor.
+ * @param scheme The scheme to use.
+ * @param hostName The host name.
+ * @param port The port.
+ * @param defaultPort The default port.
+ * @param userName The user's login id.
+ * @param password The user's credentials.
+ * @param path The file path.
+ * @param type The file type.
+ * @param queryString Parameters to use when locating or creating the file name.
+ */
+ public UrlFileName(final String scheme, final String hostName, final int port, final int defaultPort,
+ final String userName, final String password, final String path, final FileType type,
+ final String queryString)
+ {
+ super(scheme, hostName, port, defaultPort, userName, password, path, type, queryString);
+ }
+
+ @Override
+ protected void appendRootUri(final StringBuilder buffer, final boolean addPassword)
+ {
+ if (getHostName() != null && !"".equals(getHostName()))
+ {
+ super.appendRootUri(buffer, addPassword);
+ return;
+ }
+
+ buffer.append(getScheme());
+ buffer.append(":");
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/url/UrlFileNameParser.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/url/UrlFileNameParser.java
new file mode 100644
index 0000000..f97fd26
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/url/UrlFileNameParser.java
@@ -0,0 +1,129 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.url;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.provider.AbstractFileNameParser;
+import org.apache.commons.vfs2.provider.URLFileName;
+import org.apache.commons.vfs2.provider.URLFileNameParser;
+import org.apache.commons.vfs2.provider.VfsComponentContext;
+import org.apache.commons.vfs2.provider.local.GenericFileNameParser;
+
+/**
+ * Implementation for any java.net.url based filesystem.
+ * <p>
+ * Composite of URLFilenameParser and GenericFilenameParser
+ */
+public class UrlFileNameParser extends AbstractFileNameParser
+{
+ private final URLFileNameParser url = new URLFileNameParser(80);
+ private final GenericFileNameParser generic = new GenericFileNameParser();
+
+ public UrlFileNameParser()
+ {
+ super();
+ }
+
+ @Override
+ public boolean encodeCharacter(final char ch)
+ {
+ return super.encodeCharacter(ch) || ch == '?';
+ }
+
+ /**
+ * Parse a URI.
+ * @param context The component context.
+ * @param base The base FileName.
+ * @param uri The target file name.
+ * @return The FileName.
+ * @throws FileSystemException if an error occurs
+ */
+ @Override
+ public FileName parseUri(final VfsComponentContext context, final FileName base, final String uri)
+ throws FileSystemException
+ {
+ if (isUrlBased(base, uri))
+ {
+ return url.parseUri(context, base, uri);
+ }
+
+ return generic.parseUri(context, base, uri);
+ }
+
+ /**
+ * Guess if the given file name is an URL with host or not.
+ * <p>
+ * VFS treats such URLs differently.
+ * <p>
+ * A file name is URL-based if the base is a {@code URLFileName} or there are only 2 slashes
+ * after the scheme.
+ * e.g: {@code http://host/path}, {@code file:/path/to/file}, {@code file:///path/to/file}.
+ * @param base The filename is relative to this base.
+ * @param filename The filename.
+ * @return true if filename contains two slashes or base was URLFileName.
+ */
+ protected boolean isUrlBased(final FileName base, final String filename)
+ {
+ if (base instanceof URLFileName)
+ {
+ return true;
+ }
+
+ return countSlashes(filename) == 2;
+ }
+
+ /**
+ * This method counts the slashes after the scheme.
+ *
+ * @param filename The file name.
+ * @return number of slashes
+ */
+ protected int countSlashes(final String filename)
+ {
+ int state = 0;
+ int nuofSlash = 0;
+ for (int pos = 0; pos < filename.length(); pos++)
+ {
+ final char c = filename.charAt(pos);
+ if (state == 0)
+ {
+ if (c >= 'a' && c <= 'z')
+ {
+ continue;
+ }
+ if (c == ':')
+ {
+ state++;
+ continue;
+ }
+ }
+ else if (state == 1)
+ {
+ if (c == '/')
+ {
+ nuofSlash++;
+ }
+ else
+ {
+ return nuofSlash;
+ }
+ }
+ }
+ return nuofSlash;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/url/UrlFileObject.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/url/UrlFileObject.java
new file mode 100644
index 0000000..4ff201d
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/url/UrlFileObject.java
@@ -0,0 +1,169 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.url;
+
+import java.io.FileNotFoundException;
+import java.io.InputStream;
+import java.net.HttpURLConnection;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+
+import org.apache.commons.httpclient.URIException;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileObject;
+import org.apache.commons.vfs2.provider.URLFileName;
+
+/**
+ * A {@link org.apache.commons.vfs2.FileObject FileObject}
+ * implementation backed by a {@link URL}.
+ * <p>
+ * TODO - Implement set lastModified and get/set attribute
+ * <p>
+ * TODO - Implement getOutputStream().
+ */
+public class UrlFileObject extends AbstractFileObject<UrlFileSystem>
+{
+ private URL url;
+
+ protected UrlFileObject(final UrlFileSystem fs,
+ final AbstractFileName fileName)
+ {
+ super(fileName, fs);
+ }
+
+ /**
+ * Attaches this file object to its file resource. This method is called
+ * before any of the doBlah() or onBlah() methods. Sub-classes can use
+ * this method to perform lazy initialisation.
+ */
+ @Override
+ protected void doAttach() throws Exception
+ {
+ if (url == null)
+ {
+ // url = new URL(getName().getURI());
+ url = createURL(getName());
+ }
+ }
+
+ protected URL createURL(final FileName name) throws MalformedURLException, FileSystemException, URIException
+ {
+ if (name instanceof URLFileName)
+ {
+ final URLFileName urlName = (URLFileName) getName();
+
+ // TODO: charset
+ return new URL(urlName.getURIEncoded(null));
+ }
+ return new URL(getName().getURI());
+ }
+
+ /**
+ * Determines the type of the file.
+ */
+ @Override
+ protected FileType doGetType() throws Exception
+ {
+ try
+ {
+ // Attempt to connect & check status
+ final URLConnection conn = url.openConnection();
+ final InputStream in = conn.getInputStream();
+ try
+ {
+ if (conn instanceof HttpURLConnection)
+ {
+ final int status = ((HttpURLConnection) conn).getResponseCode();
+ // 200 is good, maybe add more later...
+ if (HttpURLConnection.HTTP_OK != status)
+ {
+ return FileType.IMAGINARY;
+ }
+ }
+
+ return FileType.FILE;
+ }
+ finally
+ {
+ in.close();
+ }
+ }
+ catch (final FileNotFoundException e)
+ {
+ return FileType.IMAGINARY;
+ }
+ }
+
+ /**
+ * Returns the size of the file content (in bytes).
+ */
+ @Override
+ protected long doGetContentSize() throws Exception
+ {
+ final URLConnection conn = url.openConnection();
+ final InputStream in = conn.getInputStream();
+ try
+ {
+ return conn.getContentLength();
+ }
+ finally
+ {
+ in.close();
+ }
+ }
+
+ /**
+ * Returns the last modified time of this file.
+ */
+ @Override
+ protected long doGetLastModifiedTime()
+ throws Exception
+ {
+ final URLConnection conn = url.openConnection();
+ final InputStream in = conn.getInputStream();
+ try
+ {
+ return conn.getLastModified();
+ }
+ finally
+ {
+ in.close();
+ }
+ }
+
+ /**
+ * Lists the children of the file.
+ */
+ @Override
+ protected String[] doListChildren() throws Exception
+ {
+ throw new FileSystemException("Not implemented.");
+ }
+
+ /**
+ * Creates an input stream to read the file content from.
+ */
+ @Override
+ protected InputStream doGetInputStream() throws Exception
+ {
+ return url.openStream();
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/url/UrlFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/url/UrlFileProvider.java
new file mode 100644
index 0000000..507280c
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/url/UrlFileProvider.java
@@ -0,0 +1,105 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.url;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemConfigBuilder;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.AbstractFileProvider;
+
+/**
+ * A file provider backed by Java's URL API.
+ */
+public class UrlFileProvider
+ extends AbstractFileProvider
+{
+ /** The provider's capabilities */
+ protected static final Collection<Capability> capabilities =
+ Collections.unmodifiableCollection(Arrays.asList(new Capability[]
+ {
+ Capability.READ_CONTENT,
+ Capability.URI,
+ Capability.GET_LAST_MODIFIED
+ }));
+
+ public UrlFileProvider()
+ {
+ super();
+ setFileNameParser(new UrlFileNameParser());
+ }
+
+ /**
+ * Locates a file object, by absolute URI.
+ * @param baseFile The base FileObject.
+ * @param uri The uri of the file to locate.
+ * @param fileSystemOptions The FileSystemOptions
+ * @return The FileObject
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public synchronized FileObject findFile(final FileObject baseFile,
+ final String uri,
+ final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ try
+ {
+ final URL url = new URL(uri);
+
+ final URL rootUrl = new URL(url, "/");
+ final String key = this.getClass().getName() + rootUrl.toString();
+ FileSystem fs = findFileSystem(key, fileSystemOptions);
+ if (fs == null)
+ {
+ final String extForm = rootUrl.toExternalForm();
+ final FileName rootName =
+ getContext().parseURI(extForm);
+ // final FileName rootName =
+ // new BasicFileName(rootUrl, FileName.ROOT_PATH);
+ fs = new UrlFileSystem(rootName, fileSystemOptions);
+ addFileSystem(key, fs);
+ }
+ return fs.resolveFile(url.getPath());
+ }
+ catch (final MalformedURLException e)
+ {
+ throw new FileSystemException("vfs.provider.url/badly-formed-uri.error", uri, e);
+ }
+ }
+
+ @Override
+ public FileSystemConfigBuilder getConfigBuilder()
+ {
+ return org.apache.commons.vfs2.provider.res.ResourceFileSystemConfigBuilder.getInstance();
+ }
+
+ @Override
+ public Collection<Capability> getCapabilities()
+ {
+ return capabilities;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/url/UrlFileSystem.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/url/UrlFileSystem.java
new file mode 100644
index 0000000..5e2d198
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/url/UrlFileSystem.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.url;
+
+import java.util.Collection;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileSystem;
+
+/**
+ * A File system backed by Java's URL API.
+ */
+public class UrlFileSystem
+ extends AbstractFileSystem
+{
+ protected UrlFileSystem(final FileName rootName, final FileSystemOptions fileSystemOptions)
+ {
+ super(rootName, null, fileSystemOptions);
+ }
+
+ /**
+ * Creates a file object.
+ */
+ @Override
+ protected FileObject createFile(final AbstractFileName name)
+ {
+ return new UrlFileObject(this, name);
+ }
+
+ /**
+ * Returns the capabilities of this file system.
+ */
+ @Override
+ protected void addCapabilities(final Collection<Capability> caps)
+ {
+ caps.addAll(UrlFileProvider.capabilities);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/url/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/url/package.html
new file mode 100644
index 0000000..2200b03
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/url/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>The Default File Provider, which wraps java.net.URL.</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/ExceptionConverter.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/ExceptionConverter.java
new file mode 100644
index 0000000..122feb0
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/ExceptionConverter.java
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.webdav;
+
+import java.lang.reflect.Constructor;
+
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.jackrabbit.webdav.DavConstants;
+import org.apache.jackrabbit.webdav.DavException;
+import org.apache.jackrabbit.webdav.client.methods.DavMethod;
+import org.apache.jackrabbit.webdav.xml.DomUtil;
+import org.w3c.dom.Element;
+
+/**
+ * {@code ExceptionConverter} converts WebDAV exceptions into FileSystemExceptions.
+ * @since 2.0
+ */
+public final class ExceptionConverter
+{
+ // avoid instanciation
+ private ExceptionConverter()
+ {
+ }
+
+ public static FileSystemException generate(final DavException davExc) throws FileSystemException
+ {
+ return generate(davExc, null);
+ }
+
+ public static FileSystemException generate(final DavException davExc, final DavMethod method)
+ throws FileSystemException
+ {
+ String msg = davExc.getMessage();
+ if (davExc.hasErrorCondition())
+ {
+ try
+ {
+ final Element error = davExc.toXml(DomUtil.BUILDER_FACTORY.newDocumentBuilder().newDocument());
+ if (DomUtil.matches(error, DavException.XML_ERROR, DavConstants.NAMESPACE))
+ {
+ if (DomUtil.hasChildElement(error, "exception", null))
+ {
+ final Element exc = DomUtil.getChildElement(error, "exception", null);
+ if (DomUtil.hasChildElement(exc, "message", null))
+ {
+ msg = DomUtil.getChildText(exc, "message", null);
+ }
+ if (DomUtil.hasChildElement(exc, "class", null))
+ {
+ final Class<?> cl = Class.forName(DomUtil.getChildText(exc, "class", null));
+ final Constructor<?> excConstr = cl.getConstructor(new Class[]{String.class});
+ if (excConstr != null)
+ {
+ final Object o = excConstr.newInstance(new Object[]{msg});
+ if (o instanceof FileSystemException)
+ {
+ return (FileSystemException) o;
+ }
+ else if (o instanceof Exception)
+ {
+ return new FileSystemException(msg, (Exception) o);
+ }
+ }
+ }
+ }
+ }
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException(e);
+ }
+ }
+
+ return new FileSystemException(msg);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileContentInfoFactory.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileContentInfoFactory.java
new file mode 100644
index 0000000..f738da9
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileContentInfoFactory.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.webdav;
+
+import org.apache.commons.vfs2.FileContent;
+import org.apache.commons.vfs2.FileContentInfo;
+import org.apache.commons.vfs2.FileContentInfoFactory;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.impl.DefaultFileContentInfo;
+import org.apache.commons.vfs2.provider.URLFileName;
+import org.apache.commons.vfs2.util.FileObjectUtils;
+import org.apache.jackrabbit.webdav.property.DavProperty;
+import org.apache.jackrabbit.webdav.property.DavPropertyName;
+import org.apache.jackrabbit.webdav.property.DavPropertyNameSet;
+import org.apache.jackrabbit.webdav.property.DavPropertySet;
+
+/**
+ * Determines the content information for files accessed via WebDAV.
+ *
+ * @since 2.0
+ */
+public class WebdavFileContentInfoFactory implements FileContentInfoFactory
+{
+ @Override
+ public FileContentInfo create(final FileContent fileContent) throws FileSystemException
+ {
+ final WebdavFileObject file = (WebdavFileObject) FileObjectUtils
+ .getAbstractFileObject(fileContent.getFile());
+
+ String contentType = null;
+ String contentEncoding = null;
+
+ final DavPropertyNameSet nameSet = new DavPropertyNameSet();
+ nameSet.add(DavPropertyName.GETCONTENTTYPE);
+ final DavPropertySet propertySet = file.getProperties((URLFileName) file.getName(), nameSet, true);
+
+ DavProperty property = propertySet.get(DavPropertyName.GETCONTENTTYPE);
+ if (property != null)
+ {
+ contentType = (String) property.getValue();
+ }
+ property = propertySet.get(WebdavFileObject.RESPONSE_CHARSET);
+ if (property != null)
+ {
+ contentEncoding = (String) property.getValue();
+ }
+
+ return new DefaultFileContentInfo(contentType, contentEncoding);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileNameParser.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileNameParser.java
new file mode 100644
index 0000000..6386a74
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileNameParser.java
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.webdav;
+
+import org.apache.commons.vfs2.provider.FileNameParser;
+import org.apache.commons.vfs2.provider.http.HttpFileNameParser;
+
+/**
+ * Implementation for http. set default port to 80
+ * @since 2.0
+ */
+public class WebdavFileNameParser extends HttpFileNameParser
+{
+ private static final WebdavFileNameParser INSTANCE = new WebdavFileNameParser();
+
+ public WebdavFileNameParser()
+ {
+ super();
+ }
+
+ public static FileNameParser getInstance()
+ {
+ return INSTANCE;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileObject.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileObject.java
new file mode 100644
index 0000000..1e30859
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileObject.java
@@ -0,0 +1,802 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.webdav;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.net.HttpURLConnection;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.commons.httpclient.HttpMethod;
+import org.apache.commons.httpclient.HttpMethodBase;
+import org.apache.commons.httpclient.HttpStatus;
+import org.apache.commons.httpclient.URIException;
+import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
+import org.apache.commons.httpclient.methods.RequestEntity;
+import org.apache.commons.httpclient.params.HttpMethodParams;
+import org.apache.commons.httpclient.util.DateUtil;
+import org.apache.commons.vfs2.FileContentInfoFactory;
+import org.apache.commons.vfs2.FileNotFolderException;
+import org.apache.commons.vfs2.FileNotFoundException;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.NameScope;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.DefaultFileContent;
+import org.apache.commons.vfs2.provider.URLFileName;
+import org.apache.commons.vfs2.provider.http.HttpFileObject;
+import org.apache.commons.vfs2.util.FileObjectUtils;
+import org.apache.commons.vfs2.util.MonitorOutputStream;
+import org.apache.jackrabbit.webdav.DavConstants;
+import org.apache.jackrabbit.webdav.DavException;
+import org.apache.jackrabbit.webdav.MultiStatus;
+import org.apache.jackrabbit.webdav.MultiStatusResponse;
+import org.apache.jackrabbit.webdav.client.methods.CheckinMethod;
+import org.apache.jackrabbit.webdav.client.methods.CheckoutMethod;
+import org.apache.jackrabbit.webdav.client.methods.DavMethod;
+import org.apache.jackrabbit.webdav.client.methods.DeleteMethod;
+import org.apache.jackrabbit.webdav.client.methods.MkColMethod;
+import org.apache.jackrabbit.webdav.client.methods.MoveMethod;
+import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
+import org.apache.jackrabbit.webdav.client.methods.PropPatchMethod;
+import org.apache.jackrabbit.webdav.client.methods.PutMethod;
+import org.apache.jackrabbit.webdav.client.methods.UncheckoutMethod;
+import org.apache.jackrabbit.webdav.client.methods.VersionControlMethod;
+import org.apache.jackrabbit.webdav.property.DavProperty;
+import org.apache.jackrabbit.webdav.property.DavPropertyName;
+import org.apache.jackrabbit.webdav.property.DavPropertyNameSet;
+import org.apache.jackrabbit.webdav.property.DavPropertySet;
+import org.apache.jackrabbit.webdav.property.DefaultDavProperty;
+import org.apache.jackrabbit.webdav.version.DeltaVConstants;
+import org.apache.jackrabbit.webdav.version.VersionControlledResource;
+import org.apache.jackrabbit.webdav.xml.Namespace;
+import org.w3c.dom.Node;
+
+/**
+ * A WebDAV file.
+ *
+ * @since 2.0
+ */
+public class WebdavFileObject extends HttpFileObject<WebdavFileSystem>
+{
+ /**
+ * An OutputStream that writes to a Webdav resource.
+ * <p>
+ * TODO - Use piped stream to avoid temporary file.
+ */
+ private class WebdavOutputStream extends MonitorOutputStream
+ {
+ private final WebdavFileObject file;
+
+ public WebdavOutputStream(final WebdavFileObject file)
+ {
+ super(new ByteArrayOutputStream());
+ this.file = file;
+ }
+
+ private boolean createVersion(final String urlStr)
+ {
+ try
+ {
+ final VersionControlMethod method = new VersionControlMethod(urlStr);
+ setupMethod(method);
+ execute(method);
+ return true;
+ }
+ catch (final Exception ex)
+ {
+ return false;
+ }
+ }
+
+ /**
+ * Called after this stream is closed.
+ */
+ @Override
+ protected void onClose() throws IOException
+ {
+ final RequestEntity entity = new ByteArrayRequestEntity(((ByteArrayOutputStream) out).toByteArray());
+ final URLFileName fileName = (URLFileName) getName();
+ final String urlStr = toUrlString(fileName);
+ if (builder.isVersioning(getFileSystem().getFileSystemOptions()))
+ {
+ DavPropertySet set = null;
+ boolean fileExists = true;
+ boolean isCheckedIn = true;
+ try
+ {
+ set = getPropertyNames(fileName);
+ }
+ catch (final FileNotFoundException fnfe)
+ {
+ fileExists = false;
+ }
+ if (fileExists && set != null)
+ {
+ if (set.contains(VersionControlledResource.CHECKED_OUT))
+ {
+ isCheckedIn = false;
+ }
+ else if (!set.contains(VersionControlledResource.CHECKED_IN))
+ {
+ DavProperty prop = set.get(VersionControlledResource.AUTO_VERSION);
+ if (prop != null)
+ {
+ prop = getProperty(fileName, VersionControlledResource.AUTO_VERSION);
+ if (DeltaVConstants.XML_CHECKOUT_CHECKIN.equals(prop.getValue()))
+ {
+ createVersion(urlStr);
+ }
+ }
+ }
+ }
+ if (fileExists && isCheckedIn)
+ {
+ try
+ {
+ final CheckoutMethod checkout = new CheckoutMethod(urlStr);
+ setupMethod(checkout);
+ execute(checkout);
+ isCheckedIn = false;
+ }
+ catch (final FileSystemException ex)
+ {
+ // Ignore the exception checking out.
+ }
+ }
+
+ try
+ {
+ final PutMethod method = new PutMethod(urlStr);
+ method.setRequestEntity(entity);
+ setupMethod(method);
+ execute(method);
+ setUserName(fileName, urlStr);
+ }
+ catch (final FileSystemException ex)
+ {
+ if (!isCheckedIn)
+ {
+ try
+ {
+ final UncheckoutMethod method = new UncheckoutMethod(urlStr);
+ setupMethod(method);
+ execute(method);
+ isCheckedIn = true;
+ }
+ catch (final Exception e)
+ {
+ // Ignore the exception. Going to throw original.
+ }
+ throw ex;
+ }
+ }
+ if (!fileExists)
+ {
+ createVersion(urlStr);
+ try
+ {
+ final DavPropertySet props = getPropertyNames(fileName);
+ isCheckedIn = !props.contains(VersionControlledResource.CHECKED_OUT);
+ }
+ catch (final FileNotFoundException fnfe)
+ {
+ // Ignore the error
+ }
+ }
+ if (!isCheckedIn)
+ {
+ final CheckinMethod checkin = new CheckinMethod(urlStr);
+ setupMethod(checkin);
+ execute(checkin);
+ }
+ }
+ else
+ {
+ final PutMethod method = new PutMethod(urlStr);
+ method.setRequestEntity(entity);
+ setupMethod(method);
+ execute(method);
+ try
+ {
+ setUserName(fileName, urlStr);
+ }
+ catch (final IOException e)
+ {
+ // Ignore the exception if unable to set the user name.
+ }
+ }
+ ((DefaultFileContent) this.file.getContent()).resetAttributes();
+ }
+
+ private void setUserName(final URLFileName fileName, final String urlStr)
+ throws IOException
+ {
+ final List<DefaultDavProperty> list = new ArrayList<DefaultDavProperty>();
+ String name = builder.getCreatorName(getFileSystem().getFileSystemOptions());
+ final String userName = fileName.getUserName();
+ if (name == null)
+ {
+ name = userName;
+ }
+ else
+ {
+ if (userName != null)
+ {
+ final String comment = "Modified by user " + userName;
+ list.add(new DefaultDavProperty(DeltaVConstants.COMMENT, comment));
+ }
+ }
+ list.add(new DefaultDavProperty(DeltaVConstants.CREATOR_DISPLAYNAME, name));
+ final PropPatchMethod method = new PropPatchMethod(urlStr, list);
+ setupMethod(method);
+ execute(method);
+ }
+ }
+
+ /** The character set property name. */
+ public static final DavPropertyName RESPONSE_CHARSET = DavPropertyName.create(
+ "response-charset");
+
+ /** The FileSystemConfigBuilder */
+ private final WebdavFileSystemConfigBuilder builder;
+
+ private final WebdavFileSystem fileSystem;
+
+ protected WebdavFileObject(final AbstractFileName name, final WebdavFileSystem fileSystem)
+ {
+ super(name, fileSystem, WebdavFileSystemConfigBuilder.getInstance());
+ this.fileSystem = fileSystem;
+ builder = (WebdavFileSystemConfigBuilder) WebdavFileSystemConfigBuilder.getInstance();
+ }
+
+ protected void configureMethod(final HttpMethodBase httpMethod)
+ {
+ httpMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, WebdavMethodRetryHandler.getInstance());
+ }
+
+ /**
+ * Creates this file as a folder.
+ */
+ @Override
+ protected void doCreateFolder() throws Exception
+ {
+ final DavMethod method = new MkColMethod(toUrlString((URLFileName) getName()));
+ setupMethod(method);
+ try
+ {
+ execute(method);
+ }
+ catch (final FileSystemException fse)
+ {
+ throw new FileSystemException("vfs.provider.webdav/create-collection.error", getName(),
+ fse);
+ }
+ }
+
+ /**
+ * Deletes the file.
+ */
+ @Override
+ protected void doDelete() throws Exception
+ {
+ final DavMethod method = new DeleteMethod(toUrlString((URLFileName) getName()));
+ setupMethod(method);
+ execute(method);
+ }
+
+ /**
+ * Returns the properties of the Webdav resource.
+ */
+ @Override
+ protected Map<String, Object> doGetAttributes() throws Exception
+ {
+ final Map<String, Object> attributes = new HashMap<String, Object>();
+ try
+ {
+ final URLFileName fileName = (URLFileName) getName();
+ DavPropertySet properties = getProperties(fileName, DavConstants.PROPFIND_ALL_PROP,
+ new DavPropertyNameSet(), false);
+ @SuppressWarnings("unchecked") // iterator() is documented to return DavProperty instances
+ final
+ Iterator<DavProperty> iter = properties.iterator();
+ while (iter.hasNext())
+ {
+ final DavProperty property = iter.next();
+ attributes.put(property.getName().toString(), property.getValue());
+ }
+ properties = getPropertyNames(fileName);
+ @SuppressWarnings("unchecked") // iterator() is documented to return DavProperty instances
+ final
+ Iterator<DavProperty> iter2 = properties.iterator();
+ while (iter2.hasNext())
+ {
+ DavProperty property = iter2.next();
+ if (!attributes.containsKey(property.getName().getName()))
+ {
+ property = getProperty(fileName, property.getName());
+ if (property != null)
+ {
+ final Object name = property.getName();
+ final Object value = property.getValue();
+ if (name != null && value != null)
+ {
+ attributes.put(name.toString(), value);
+ }
+ }
+ }
+ }
+ return attributes;
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("vfs.provider.webdav/get-attributes.error", getName(), e);
+ }
+ }
+
+ /**
+ * Returns the size of the file content (in bytes).
+ */
+ @Override
+ protected long doGetContentSize() throws Exception
+ {
+ final DavProperty property = getProperty((URLFileName) getName(),
+ DavConstants.PROPERTY_GETCONTENTLENGTH);
+ if (property != null)
+ {
+ final String value = (String) property.getValue();
+ return Long.parseLong(value);
+ }
+ return 0;
+ }
+
+ /**
+ * Returns the last modified time of this file. Is only called if
+ * {@link #doGetType} does not return {@link FileType#IMAGINARY}.
+ */
+ @Override
+ protected long doGetLastModifiedTime() throws Exception
+ {
+ final DavProperty property = getProperty((URLFileName) getName(),
+ DavConstants.PROPERTY_GETLASTMODIFIED);
+ if (property != null)
+ {
+ final String value = (String) property.getValue();
+ return DateUtil.parseDate(value).getTime();
+ }
+ return 0;
+ }
+
+ @Override
+ protected OutputStream doGetOutputStream(final boolean bAppend) throws Exception
+ {
+ return new WebdavOutputStream(this);
+ }
+
+ /**
+ * Determines the type of this file. Must not return null. The return
+ * value of this method is cached, so the implementation can be expensive.
+ */
+ @Override
+ protected FileType doGetType() throws Exception
+ {
+ try
+ {
+ return isDirectory((URLFileName) getName()) ? FileType.FOLDER : FileType.FILE;
+ }
+ catch (final FileNotFolderException fnfe)
+ {
+ return FileType.IMAGINARY;
+ }
+ catch (final FileNotFoundException fnfe)
+ {
+ return FileType.IMAGINARY;
+ }
+
+ }
+
+ /**
+ * Determines if this file can be written to. Is only called if
+ * {@link #doGetType} does not return {@link FileType#IMAGINARY}.
+ * <p>
+ * This implementation always returns true.
+ *
+ * @return true if the file is writable.
+ * @throws Exception if an error occurs.
+ */
+ @Override
+ protected boolean doIsWriteable() throws Exception
+ {
+ return true;
+ }
+
+ /**
+ * Lists the children of the file.
+ */
+ @Override
+ protected String[] doListChildren() throws Exception
+ {
+ // use doListChildrenResolved for performance
+ return null;
+ }
+
+ /**
+ * Lists the children of the file.
+ */
+ @Override
+ protected FileObject[] doListChildrenResolved() throws Exception
+ {
+ PropFindMethod method = null;
+ try
+ {
+ final URLFileName name = (URLFileName) getName();
+ if (isDirectory(name))
+ {
+ final DavPropertyNameSet nameSet = new DavPropertyNameSet();
+ nameSet.add(DavPropertyName.create(DavConstants.PROPERTY_DISPLAYNAME));
+
+ method = new PropFindMethod(toUrlString(name), nameSet,
+ DavConstants.DEPTH_1);
+
+ execute(method);
+ final List<WebdavFileObject> vfs = new ArrayList<WebdavFileObject>();
+ if (method.succeeded())
+ {
+ final MultiStatusResponse[] responses =
+ method.getResponseBodyAsMultiStatus().getResponses();
+
+ for (final MultiStatusResponse response : responses)
+ {
+ if (isCurrentFile(response.getHref(), name))
+ {
+ continue;
+ }
+ final String resourceName = resourceName(response.getHref());
+ if (resourceName != null && resourceName.length() > 0)
+ {
+ final WebdavFileObject fo = (WebdavFileObject) FileObjectUtils.
+ getAbstractFileObject(getFileSystem().resolveFile(
+ getFileSystem().getFileSystemManager().
+ resolveName(getName(), resourceName,
+ NameScope.CHILD)));
+ vfs.add(fo);
+ }
+ }
+ }
+ return vfs.toArray(new WebdavFileObject[vfs.size()]);
+ }
+ throw new FileNotFolderException(getName());
+ }
+ catch (final FileNotFolderException fnfe)
+ {
+ throw fnfe;
+ }
+ catch (final DavException e)
+ {
+ throw new FileSystemException(e.getMessage(), e);
+ }
+ catch (final IOException e)
+ {
+ throw new FileSystemException(e.getMessage(), e);
+ }
+ finally
+ {
+ if (method != null)
+ {
+ method.releaseConnection();
+ }
+ }
+ }
+
+ /**
+ * Rename the file.
+ */
+ @Override
+ protected void doRename(final FileObject newFile) throws Exception
+ {
+ final String url = encodePath(toUrlString((URLFileName) getName()));
+ final String dest = toUrlString((URLFileName) newFile.getName(), false);
+ final DavMethod method = new MoveMethod(url, dest, false);
+ setupMethod(method);
+ execute(method);
+ }
+
+ /**
+ * Sets an attribute of this file. Is only called if {@link #doGetType}
+ * does not return {@link FileType#IMAGINARY}.
+ */
+ @Override
+ protected void doSetAttribute(final String attrName, final Object value)
+ throws Exception
+ {
+ try
+ {
+ final URLFileName fileName = (URLFileName) getName();
+ final String urlStr = toUrlString(fileName);
+ final DavPropertySet properties = new DavPropertySet();
+ final DavPropertyNameSet propertyNameSet = new DavPropertyNameSet();
+ final DavProperty property = new DefaultDavProperty(attrName, value, Namespace.EMPTY_NAMESPACE);
+ if (value != null)
+ {
+ properties.add(property);
+ }
+ else
+ {
+ propertyNameSet.add(property.getName()); // remove property
+ }
+
+ final PropPatchMethod method = new PropPatchMethod(urlStr, properties, propertyNameSet);
+ setupMethod(method);
+ execute(method);
+ if (!method.succeeded())
+ {
+ throw new FileSystemException("Property '" + attrName + "' could not be set.");
+ }
+ }
+ catch (final FileSystemException fse)
+ {
+ throw fse;
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("vfs.provider.webdav/set-attributes", e, getName(), attrName);
+ }
+ }
+
+ /**
+ * Execute a 'Workspace' operation.
+ *
+ * @param method The DavMethod to invoke.
+ * @throws FileSystemException If an error occurs.
+ */
+ private void execute(final DavMethod method) throws FileSystemException
+ {
+ try
+ {
+ final int status = fileSystem.getClient().executeMethod(method);
+ if (status == HttpURLConnection.HTTP_NOT_FOUND
+ || status == HttpURLConnection.HTTP_GONE)
+ {
+ throw new FileNotFoundException(method.getURI());
+ }
+ method.checkSuccess();
+ }
+ catch (final FileSystemException fse)
+ {
+ throw fse;
+ }
+ catch (final IOException e)
+ {
+ throw new FileSystemException(e);
+ }
+ catch (final DavException e)
+ {
+ throw ExceptionConverter.generate(e);
+ }
+ finally
+ {
+ if (method != null)
+ {
+ method.releaseConnection();
+ }
+ }
+ }
+
+ @Override
+ protected FileContentInfoFactory getFileContentInfoFactory()
+ {
+ return new WebdavFileContentInfoFactory();
+ }
+
+ DavPropertySet getProperties(final URLFileName name) throws FileSystemException
+ {
+ return getProperties(name, DavConstants.PROPFIND_ALL_PROP, new DavPropertyNameSet(),
+ false);
+ }
+
+ DavPropertySet getProperties(final URLFileName name, final DavPropertyNameSet nameSet, final boolean addEncoding)
+ throws FileSystemException
+ {
+ return getProperties(name, DavConstants.PROPFIND_BY_PROPERTY, nameSet, addEncoding);
+ }
+
+ DavPropertySet getProperties(final URLFileName name, final int type, final DavPropertyNameSet nameSet,
+ final boolean addEncoding)
+ throws FileSystemException
+ {
+ try
+ {
+ final String urlStr = toUrlString(name);
+ final PropFindMethod method = new PropFindMethod(urlStr, type, nameSet, DavConstants.DEPTH_0);
+ setupMethod(method);
+ execute(method);
+ if (method.succeeded())
+ {
+ final MultiStatus multiStatus = method.getResponseBodyAsMultiStatus();
+ final MultiStatusResponse response = multiStatus.getResponses()[0];
+ final DavPropertySet props = response.getProperties(HttpStatus.SC_OK);
+ if (addEncoding)
+ {
+ final DavProperty prop = new DefaultDavProperty(RESPONSE_CHARSET,
+ method.getResponseCharSet());
+ props.add(prop);
+ }
+ return props;
+ }
+ return new DavPropertySet();
+ }
+ catch (final FileSystemException fse)
+ {
+ throw fse;
+ }
+ catch (final Exception e)
+ {
+ throw new FileSystemException("vfs.provider.webdav/get-property.error", e, getName(), name, type,
+ nameSet.getContent(), addEncoding);
+ }
+ }
+
+ DavProperty getProperty(final URLFileName fileName, final DavPropertyName name)
+ throws FileSystemException
+ {
+ final DavPropertyNameSet nameSet = new DavPropertyNameSet();
+ nameSet.add(name);
+ final DavPropertySet propertySet = getProperties(fileName, nameSet, false);
+ return propertySet.get(name);
+ }
+
+ DavProperty getProperty(final URLFileName fileName, final String property)
+ throws FileSystemException
+ {
+ return getProperty(fileName, DavPropertyName.create(property));
+ }
+
+
+ DavPropertySet getPropertyNames(final URLFileName name) throws FileSystemException
+ {
+ return getProperties(name, DavConstants.PROPFIND_PROPERTY_NAMES,
+ new DavPropertyNameSet(), false);
+ }
+
+ /**
+ * Convert the FileName to an encoded url String.
+ *
+ * @param name The FileName.
+ * @return The encoded URL String.
+ */
+ private String hrefString(final URLFileName name)
+ {
+ final URLFileName newFile = new URLFileName("http", name.getHostName(), name.getPort(),
+ name.getDefaultPort(), null, null,
+ name.getPath(), name.getType(), name.getQueryString());
+ try
+ {
+ return newFile.getURIEncoded(this.getUrlCharset());
+ }
+ catch (final Exception e)
+ {
+ return name.getURI();
+ }
+ }
+
+ private boolean isCurrentFile(final String href, final URLFileName fileName)
+ {
+ String name = hrefString(fileName);
+ if (href.endsWith("/") && !name.endsWith("/"))
+ {
+ name += "/";
+ }
+ return href.equals(name) || href.equals(fileName.getPath());
+ }
+
+ private boolean isDirectory(final URLFileName name) throws IOException
+ {
+ try
+ {
+ final DavProperty property = getProperty(name, DavConstants.PROPERTY_RESOURCETYPE);
+ Node node;
+ if (property != null && (node = (Node) property.getValue()) != null)
+ {
+ return node.getLocalName().equals(DavConstants.XML_COLLECTION);
+ }
+ else
+ {
+ return false;
+ }
+ }
+ catch (final FileNotFoundException fse)
+ {
+ throw new FileNotFolderException(name);
+ }
+ }
+
+ /**
+ * Returns the resource name from the path.
+ *
+ * @param path the path to the file.
+ * @return The resource name
+ */
+ private String resourceName(String path)
+ {
+ if (path.endsWith("/"))
+ {
+ path = path.substring(0, path.length() - 1);
+ }
+ final int i = path.lastIndexOf("/");
+ return i >= 0 ? path.substring(i + 1) : path;
+ }
+
+ /**
+ * Prepares a Method object.
+ *
+ * @param method the HttpMethod.
+ * @throws FileSystemException if an error occurs encoding the uri.
+ * @throws URIException if the URI is in error.
+ */
+ @Override
+ protected void setupMethod(final HttpMethod method) throws FileSystemException, URIException
+ {
+ final String pathEncoded = ((URLFileName) getName()).getPathQueryEncoded(this.getUrlCharset());
+ method.setPath(pathEncoded);
+ method.setFollowRedirects(this.getFollowRedirect());
+ method.setRequestHeader("User-Agent", "Jakarta-Commons-VFS");
+ method.addRequestHeader("Cache-control", "no-cache");
+ method.addRequestHeader("Cache-store", "no-store");
+ method.addRequestHeader("Pragma", "no-cache");
+ method.addRequestHeader("Expires", "0");
+ }
+
+ private String toUrlString(final URLFileName name)
+ {
+ return toUrlString(name, true);
+ }
+
+ /**
+ * Converts the given URLFileName to an encoded URL String.
+ *
+ * @param name The FileName.
+ * @param includeUserInfo true if user information should be included.
+ * @return The encoded URL String.
+ */
+ private String toUrlString(final URLFileName name, final boolean includeUserInfo)
+ {
+ String user = null;
+ String password = null;
+ if (includeUserInfo)
+ {
+ user = name.getUserName();
+ password = name.getPassword();
+ }
+ final URLFileName newFile = new URLFileName("http", name.getHostName(), name.getPort(),
+ name.getDefaultPort(), user, password,
+ name.getPath(), name.getType(), name.getQueryString());
+ try
+ {
+ return newFile.getURIEncoded(this.getUrlCharset());
+ }
+ catch (final Exception e)
+ {
+ return name.getURI();
+ }
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileProvider.java
new file mode 100644
index 0000000..df288b3
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileProvider.java
@@ -0,0 +1,124 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.webdav;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemConfigBuilder;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.UserAuthenticationData;
+import org.apache.commons.vfs2.provider.GenericFileName;
+import org.apache.commons.vfs2.provider.http.HttpClientFactory;
+import org.apache.commons.vfs2.provider.http.HttpFileProvider;
+import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
+
+/**
+ * A provider for WebDAV.
+ *
+ * @since 2.0
+ */
+public class WebdavFileProvider
+ extends HttpFileProvider
+{
+ /** The capabilities of the WebDAV provider */
+ protected static final Collection<Capability> capabilities =
+ Collections.unmodifiableCollection(Arrays.asList(new Capability[]
+ {
+ Capability.CREATE,
+ Capability.DELETE,
+ Capability.RENAME,
+ Capability.GET_TYPE,
+ Capability.LIST_CHILDREN,
+ Capability.READ_CONTENT,
+ Capability.URI,
+ Capability.WRITE_CONTENT,
+ Capability.GET_LAST_MODIFIED,
+ Capability.ATTRIBUTES,
+ Capability.RANDOM_ACCESS_READ,
+ Capability.DIRECTORY_READ_CONTENT,
+ }));
+
+ public WebdavFileProvider()
+ {
+ super();
+
+ setFileNameParser(WebdavFileNameParser.getInstance());
+ }
+ /**
+ * Creates a {@link FileSystem}.
+ * <p>
+ * If you're looking at this method and wondering how to get a FileSystemOptions
+ * object bearing the proxy host and credentials configuration through
+ * to this method so it's used for resolving a
+ * {@link org.apache.commons.vfs2.FileObject FileObject} in the FileSystem, then be sure
+ * to use correct signature of the {@link org.apache.commons.vfs2.FileSystemManager FileSystemManager}
+ * resolveFile method.
+ * @see org.apache.commons.vfs2.impl.DefaultFileSystemManager#resolveFile(FileObject, String, FileSystemOptions)
+ */
+ @Override
+ protected FileSystem doCreateFileSystem(final FileName name, final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ // Create the file system
+ final GenericFileName rootName = (GenericFileName) name;
+ final FileSystemOptions fsOpts = fileSystemOptions == null ? new FileSystemOptions() : fileSystemOptions;
+
+ UserAuthenticationData authData = null;
+ HttpClient httpClient;
+ try
+ {
+ authData = UserAuthenticatorUtils.authenticate(fsOpts, AUTHENTICATOR_TYPES);
+
+ httpClient = HttpClientFactory.createConnection(
+ WebdavFileSystemConfigBuilder.getInstance(),
+ "http",
+ rootName.getHostName(),
+ rootName.getPort(),
+ UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
+ UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(rootName.getUserName()))),
+ UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
+ UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(rootName.getPassword()))),
+ fsOpts);
+ }
+ finally
+ {
+ UserAuthenticatorUtils.cleanup(authData);
+ }
+
+ return new WebdavFileSystem(rootName, httpClient, fsOpts);
+ }
+
+ @Override
+ public FileSystemConfigBuilder getConfigBuilder()
+ {
+ return WebdavFileSystemConfigBuilder.getInstance();
+ }
+
+
+ @Override
+ public Collection<Capability> getCapabilities()
+ {
+ return capabilities;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileSystem.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileSystem.java
new file mode 100644
index 0000000..ca1363b
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileSystem.java
@@ -0,0 +1,82 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.webdav;
+
+import java.net.URLStreamHandler;
+import java.util.Collection;
+
+import org.apache.commons.httpclient.HttpClient;
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.DefaultURLStreamHandler;
+import org.apache.commons.vfs2.provider.GenericFileName;
+import org.apache.commons.vfs2.provider.http.HttpFileSystem;
+
+/**
+ * A WebDAV file system.
+ *
+ * @since 2.0
+ */
+public class WebdavFileSystem extends HttpFileSystem
+{
+ protected WebdavFileSystem(final GenericFileName rootName, final HttpClient client,
+ final FileSystemOptions fileSystemOptions)
+ {
+ super(rootName, client, fileSystemOptions);
+ }
+
+ @Override
+ protected HttpClient getClient()
+ {
+ // make accessible
+ return super.getClient();
+ }
+
+ /**
+ * Returns the capabilities of this file system.
+ * @param caps The Capabilities to add.
+ */
+ @Override
+ protected void addCapabilities(final Collection<Capability> caps)
+ {
+ caps.addAll(WebdavFileProvider.capabilities);
+ }
+
+ /**
+ * Creates a file object. This method is called only if the requested
+ * file is not cached.
+ * @param name the FileName.
+ * @return The created FileObject.
+ */
+ @Override
+ protected FileObject createFile(final AbstractFileName name)
+ {
+
+ return new WebdavFileObject(name, this);
+ }
+
+ /**
+ * Return a URLStreamHandler.
+ * @return The URLStreamHandler.
+ */
+ public URLStreamHandler getURLStreamHandler()
+ {
+ return new DefaultURLStreamHandler(getContext(), getFileSystemOptions());
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileSystemConfigBuilder.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileSystemConfigBuilder.java
new file mode 100644
index 0000000..d2ef6d6
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileSystemConfigBuilder.java
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.webdav;
+
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.http.HttpFileSystemConfigBuilder;
+
+/**
+ * Configuration options for WebDav.
+ *
+ * @since 2.0
+ */
+public final class WebdavFileSystemConfigBuilder extends HttpFileSystemConfigBuilder
+{
+ private static final WebdavFileSystemConfigBuilder BUILDER = new WebdavFileSystemConfigBuilder();
+
+ private static final boolean DEFAULT_FOLLOW_REDIRECT = false;
+
+ private WebdavFileSystemConfigBuilder()
+ {
+ super("webdav.");
+ }
+
+ /**
+ * Gets the singleton builder.
+ *
+ * @return the singleton builder.
+ */
+ public static HttpFileSystemConfigBuilder getInstance()
+ {
+ return BUILDER;
+ }
+
+ /**
+ * The user name to be associated with changes to the file.
+ * @param opts The FileSystem options
+ * @param creatorName The creator name to be associated with the file.
+ */
+ public void setCreatorName(final FileSystemOptions opts, final String creatorName)
+ {
+ setParam(opts, "creatorName", creatorName);
+ }
+
+ /**
+ * Return the user name to be associated with changes to the file.
+ * @param opts The FileSystem options
+ * @return The creatorName.
+ */
+ public String getCreatorName(final FileSystemOptions opts)
+ {
+ return getString(opts, "creatorName");
+ }
+
+ /**
+ * Gets whether to follow redirects for the connection.
+ *
+ * @param opts
+ * The FileSystem options.
+ * @return {@code true} to follow redirects, {@code false} not to.
+ * @see #setFollowRedirect
+ * @since 2.1
+ */
+ @Override
+ public boolean getFollowRedirect(final FileSystemOptions opts)
+ {
+ return getBoolean(opts, KEY_FOLLOW_REDIRECT, DEFAULT_FOLLOW_REDIRECT);
+ }
+
+ /**
+ * Whether to use versioning.
+ * @param opts The FileSystem options.
+ * @param versioning true if versioning should be enabled.
+ */
+ public void setVersioning(final FileSystemOptions opts, final boolean versioning)
+ {
+ setParam(opts, "versioning", Boolean.valueOf(versioning));
+ }
+
+ /**
+ * The cookies to add to the request.
+ * @param opts The FileSystem options.
+ * @return true if versioning is enabled.
+ */
+ public boolean isVersioning(final FileSystemOptions opts)
+ {
+ return getBoolean(opts, "versioning", false);
+ }
+
+ /**
+ * @return The Webdav FileSystem Class object.
+ */
+ @Override
+ protected Class<? extends FileSystem> getConfigClass()
+ {
+ return WebdavFileSystem.class;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavMethodRetryHandler.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavMethodRetryHandler.java
new file mode 100644
index 0000000..72a3d5c
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavMethodRetryHandler.java
@@ -0,0 +1,50 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.webdav;
+
+import java.io.IOException;
+
+import org.apache.commons.httpclient.HttpMethod;
+import org.apache.commons.httpclient.HttpMethodRetryHandler;
+
+
+/**
+ * A retry handler which will retry a failed webdav method one time.
+ * <p>
+ * Now that webdavlib didnt support adding a MethodRetryHandler only a few operations are restartable yet.
+ *
+ * @since 2.0
+ */
+public final class WebdavMethodRetryHandler implements HttpMethodRetryHandler
+{
+ private static final WebdavMethodRetryHandler INSTANCE = new WebdavMethodRetryHandler();
+
+ private WebdavMethodRetryHandler()
+ {
+ }
+
+ public static WebdavMethodRetryHandler getInstance()
+ {
+ return INSTANCE;
+ }
+
+ @Override
+ public boolean retryMethod(final HttpMethod method, final IOException exception, final int executionCount)
+ {
+ return executionCount < 2;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/package.html
new file mode 100644
index 0000000..d39cc53
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/webdav/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>The WebDAV File Provider</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/zip/ZipFileObject.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/zip/ZipFileObject.java
new file mode 100644
index 0000000..0d5a1f2
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/zip/ZipFileObject.java
@@ -0,0 +1,171 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.zip;
+
+import java.io.InputStream;
+import java.util.HashSet;
+import java.util.zip.ZipEntry;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileObject;
+
+/**
+ * A file in a Zip file system.
+ */
+public class ZipFileObject extends AbstractFileObject<ZipFileSystem>
+{
+ /** The ZipEntry. */
+ protected ZipEntry entry;
+ private final HashSet<String> children = new HashSet<String>();
+ // protected final ZipFile file;
+
+ private FileType type;
+
+ protected ZipFileObject(final AbstractFileName name,
+ final ZipEntry entry,
+ final ZipFileSystem fs,
+ final boolean zipExists) throws FileSystemException
+ {
+ super(name, fs);
+ setZipEntry(entry);
+ if (!zipExists)
+ {
+ type = FileType.IMAGINARY;
+ }
+ }
+
+ /**
+ * Sets the details for this file object.
+ * @param entry ZIP information related to this file.
+ */
+ protected void setZipEntry(final ZipEntry entry)
+ {
+ if (this.entry != null)
+ {
+ return;
+ }
+
+ if (entry == null || entry.isDirectory())
+ {
+ type = FileType.FOLDER;
+ }
+ else
+ {
+ type = FileType.FILE;
+ }
+
+ this.entry = entry;
+ }
+
+ /**
+ * Attaches a child.
+ * <p>
+ * TODO: Shouldn't this method have package-only visibility?
+ * Cannot change this without breaking binary compatibility.
+ *
+ * @param childName The name of the child.
+ */
+ public void attachChild(final FileName childName)
+ {
+ children.add(childName.getBaseName());
+ }
+
+ /**
+ * Determines if this file can be written to.
+ *
+ * @return {@code true} if this file is writeable, {@code false} if not.
+ * @throws FileSystemException if an error occurs.
+ */
+ @Override
+ public boolean isWriteable() throws FileSystemException
+ {
+ return false;
+ }
+
+ /**
+ * Returns the file's type.
+ */
+ @Override
+ protected FileType doGetType()
+ {
+ return type;
+ }
+
+ /**
+ * Lists the children of the file.
+ */
+ @Override
+ protected String[] doListChildren()
+ {
+ try
+ {
+ if (!getType().hasChildren())
+ {
+ return null;
+ }
+ }
+ catch (final FileSystemException e)
+ {
+ // should not happen as the type has already been cached.
+ throw new RuntimeException(e);
+ }
+
+ return children.toArray(new String[children.size()]);
+ }
+
+ /**
+ * Returns the size of the file content (in bytes). Is only called if
+ * {@link #doGetType} returns {@link FileType#FILE}.
+ */
+ @Override
+ protected long doGetContentSize()
+ {
+ return entry.getSize();
+ }
+
+ /**
+ * Returns the last modified time of this file.
+ */
+ @Override
+ protected long doGetLastModifiedTime() throws Exception
+ {
+ return entry.getTime();
+ }
+
+ /**
+ * Creates an input stream to read the file content from. Is only called
+ * if {@link #doGetType} returns {@link FileType#FILE}. The input stream
+ * returned by this method is guaranteed to be closed before this
+ * method is called again.
+ */
+ @Override
+ protected InputStream doGetInputStream() throws Exception
+ {
+ // VFS-210: zip allows to gather an input stream even from a directory and will
+ // return -1 on the first read. getType should not be expensive and keeps the tests
+ // running
+ if (!getType().hasContent())
+ {
+ throw new FileSystemException("vfs.provider/read-not-file.error", getName());
+ }
+
+ return getAbstractFileSystem().getZipFile().getInputStream(entry);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/zip/ZipFileProvider.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/zip/ZipFileProvider.java
new file mode 100644
index 0000000..15cc64f
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/zip/ZipFileProvider.java
@@ -0,0 +1,82 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.zip;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractLayeredFileProvider;
+import org.apache.commons.vfs2.provider.FileProvider;
+import org.apache.commons.vfs2.provider.LayeredFileName;
+
+/**
+ * A file system provider for Zip files. Provides read-only file systems.
+ */
+public class ZipFileProvider extends AbstractLayeredFileProvider implements FileProvider
+{
+ /** The list of capabilities this provider supports */
+ protected static final Collection<Capability> capabilities =
+ Collections.unmodifiableCollection(Arrays.asList(new Capability[]
+ {
+ Capability.GET_LAST_MODIFIED,
+ Capability.GET_TYPE,
+ Capability.LIST_CHILDREN,
+ Capability.READ_CONTENT,
+ Capability.URI,
+ Capability.COMPRESS,
+ Capability.VIRTUAL
+ }));
+
+ public ZipFileProvider()
+ {
+ super();
+ }
+
+ /**
+ * Creates a layered file system. This method is called if the file system
+ * is not cached.
+ *
+ * @param scheme The URI scheme.
+ * @param file The file to create the file system on top of.
+ * @return The file system.
+ */
+ @Override
+ protected FileSystem doCreateFileSystem(final String scheme,
+ final FileObject file,
+ final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ final AbstractFileName rootName =
+ new LayeredFileName(scheme, file.getName(), FileName.ROOT_PATH, FileType.FOLDER);
+ return new ZipFileSystem(rootName, file, fileSystemOptions);
+ }
+
+ @Override
+ public Collection<Capability> getCapabilities()
+ {
+ return capabilities;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/zip/ZipFileSystem.java b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/zip/ZipFileSystem.java
new file mode 100644
index 0000000..22a8933
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/zip/ZipFileSystem.java
@@ -0,0 +1,239 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.zip;
+
+import java.io.File;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.Selectors;
+import org.apache.commons.vfs2.VfsLog;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileSystem;
+import org.apache.commons.vfs2.provider.UriParser;
+
+/**
+ * A read-only file system for Zip/Jar files.
+ */
+public class ZipFileSystem extends AbstractFileSystem
+{
+ private static final Log LOG = LogFactory.getLog(ZipFileSystem.class);
+
+ private final File file;
+ private ZipFile zipFile;
+
+ /**
+ * Cache doesn't need to be synchronized since it is read-only.
+ */
+ private final Map<FileName, FileObject> cache = new HashMap<FileName, FileObject>();
+
+ public ZipFileSystem(final AbstractFileName rootName,
+ final FileObject parentLayer,
+ final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ super(rootName, parentLayer, fileSystemOptions);
+
+ // Make a local copy of the file
+ file = parentLayer.getFileSystem().replicateFile(parentLayer, Selectors.SELECT_SELF);
+
+ // Open the Zip file
+ if (!file.exists())
+ {
+ // Don't need to do anything
+ zipFile = null;
+ return;
+ }
+
+ // zipFile = createZipFile(this.file);
+ }
+
+ @Override
+ public void init() throws FileSystemException
+ {
+ super.init();
+
+ try
+ {
+ // Build the index
+ final List<ZipFileObject> strongRef = new ArrayList<ZipFileObject>(getZipFile().size());
+ final Enumeration<? extends ZipEntry> entries = getZipFile().entries();
+ while (entries.hasMoreElements())
+ {
+ final ZipEntry entry = entries.nextElement();
+ final AbstractFileName name = (AbstractFileName) getFileSystemManager().resolveName(getRootName(),
+ UriParser.encode(entry.getName()));
+
+ // Create the file
+ ZipFileObject fileObj;
+ if (entry.isDirectory() && getFileFromCache(name) != null)
+ {
+ fileObj = (ZipFileObject) getFileFromCache(name);
+ fileObj.setZipEntry(entry);
+ continue;
+ }
+
+ fileObj = createZipFileObject(name, entry);
+ putFileToCache(fileObj);
+ strongRef.add(fileObj);
+ fileObj.holdObject(strongRef);
+
+ // Make sure all ancestors exist
+ // TODO - create these on demand
+ ZipFileObject parent;
+ for (AbstractFileName parentName = (AbstractFileName) name.getParent();
+ parentName != null;
+ fileObj = parent, parentName = (AbstractFileName) parentName.getParent())
+ {
+ // Locate the parent
+ parent = (ZipFileObject) getFileFromCache(parentName);
+ if (parent == null)
+ {
+ parent = createZipFileObject(parentName, null);
+ putFileToCache(parent);
+ strongRef.add(parent);
+ parent.holdObject(strongRef);
+ }
+
+ // Attach child to parent
+ parent.attachChild(fileObj.getName());
+ }
+ }
+ }
+ finally
+ {
+ closeCommunicationLink();
+ }
+ }
+
+ protected ZipFile getZipFile() throws FileSystemException
+ {
+ if (zipFile == null && this.file.exists())
+ {
+ final ZipFile zipFile = createZipFile(this.file);
+
+ this.zipFile = zipFile;
+ }
+
+ return zipFile;
+ }
+
+ protected ZipFileObject createZipFileObject(final AbstractFileName name,
+ final ZipEntry entry) throws FileSystemException
+ {
+ return new ZipFileObject(name, entry, this, true);
+ }
+
+ protected ZipFile createZipFile(final File file) throws FileSystemException
+ {
+ try
+ {
+ return new ZipFile(file);
+ }
+ catch (final IOException ioe)
+ {
+ throw new FileSystemException("vfs.provider.zip/open-zip-file.error", file, ioe);
+ }
+ }
+
+ @Override
+ protected void doCloseCommunicationLink()
+ {
+ // Release the zip file
+ try
+ {
+ if (zipFile != null)
+ {
+ zipFile.close();
+ zipFile = null;
+ }
+ }
+ catch (final IOException e)
+ {
+ // getLogger().warn("vfs.provider.zip/close-zip-file.error :" + file, e);
+ VfsLog.warn(getLogger(), LOG, "vfs.provider.zip/close-zip-file.error :" + file, e);
+ }
+ }
+
+ /**
+ * Returns the capabilities of this file system.
+ */
+ @Override
+ protected void addCapabilities(final Collection<Capability> caps)
+ {
+ caps.addAll(ZipFileProvider.capabilities);
+ }
+
+ /**
+ * Creates a file object.
+ */
+ @Override
+ protected FileObject createFile(final AbstractFileName name) throws FileSystemException
+ {
+ // This is only called for files which do not exist in the Zip file
+ return new ZipFileObject(name, null, this, false);
+ }
+
+ /**
+ * Adds a file object to the cache.
+ */
+ @Override
+ protected void putFileToCache(final FileObject file)
+ {
+ cache.put(file.getName(), file);
+ }
+
+ /**
+ * Returns a cached file.
+ */
+ @Override
+ protected FileObject getFileFromCache(final FileName name)
+ {
+ return cache.get(name);
+ }
+
+ /**
+ * remove a cached file.
+ */
+ @Override
+ protected void removeFileFromCache(final FileName name)
+ {
+ cache.remove(name);
+ }
+
+ /**
+ * will be called after all file-objects closed their streams.
+ protected void notifyAllStreamsClosed()
+ {
+ closeCommunicationLink();
+ }
+ */
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/provider/zip/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/zip/package.html
new file mode 100644
index 0000000..8b51eaf
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/provider/zip/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>The Zip File Provider.</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/AbstractSyncTask.java b/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/AbstractSyncTask.java
new file mode 100644
index 0000000..469a235
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/AbstractSyncTask.java
@@ -0,0 +1,490 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.tasks;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Set;
+import java.util.StringTokenizer;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.NameScope;
+import org.apache.commons.vfs2.Selectors;
+import org.apache.commons.vfs2.util.Messages;
+import org.apache.tools.ant.BuildException;
+import org.apache.tools.ant.Project;
+
+/**
+ * An abstract file synchronization task. Scans a set of source files and
+ * folders, and a destination folder, and performs actions on missing and
+ * out-of-date files. Specifically, performs actions on the following:
+ * <ul>
+ * <li>Missing destination file.
+ * <li>Missing source file.
+ * <li>Out-of-date destination file.
+ * <li>Up-to-date destination file.
+ * </ul>
+ *
+ * TODO - Deal with case where dest file maps to a child of one of the source files.<br>
+ * TODO - Deal with case where dest file already exists and is incorrect type (not file, not a folder).<br>
+ * TODO - Use visitors.<br>
+ * TODO - Add default excludes.<br>
+ * TOOD - Allow selector, mapper, filters, etc to be specified.<br>
+ * TODO - Handle source/dest directories as well.<br>
+ * TODO - Allow selector to be specified for choosing which dest files to sync.
+ */
+public abstract class AbstractSyncTask
+ extends VfsTask
+{
+ private final ArrayList<SourceInfo> srcFiles = new ArrayList<SourceInfo>();
+ private String destFileUrl;
+ private String destDirUrl;
+ private String srcDirUrl;
+ private boolean srcDirIsBase;
+ private boolean failonerror = true;
+ private String filesList;
+
+ /**
+ * Sets the destination file.
+ * @param destFile The destination file name.
+ */
+ public void setDestFile(final String destFile)
+ {
+ this.destFileUrl = destFile;
+ }
+
+ /**
+ * Sets the destination directory.
+ * @param destDir The destination directory.
+ */
+ public void setDestDir(final String destDir)
+ {
+ this.destDirUrl = destDir;
+ }
+
+ /**
+ * Sets the source file.
+ * @param srcFile The source file name.
+ */
+ public void setSrc(final String srcFile)
+ {
+ final SourceInfo src = new SourceInfo();
+ src.setFile(srcFile);
+ addConfiguredSrc(src);
+ }
+
+ /**
+ * Sets the source directory.
+ * @param srcDir The source directory.
+ */
+ public void setSrcDir(final String srcDir)
+ {
+ this.srcDirUrl = srcDir;
+ }
+
+ /**
+ * Sets whether the source directory should be consider as the base directory.
+ * @param srcDirIsBase true if the source directory is the base directory.
+ */
+ public void setSrcDirIsBase(final boolean srcDirIsBase)
+ {
+ this.srcDirIsBase = srcDirIsBase;
+ }
+
+ /**
+ * Sets whether we should fail if there was an error or not.
+ * @param failonerror true if the operation should fail if there is an error.
+ */
+ public void setFailonerror(final boolean failonerror)
+ {
+ this.failonerror = failonerror;
+ }
+
+ /**
+ * Sets whether we should fail if there was an error or not.
+ * @return true if the operation should fail if there was an error.
+ */
+ public boolean isFailonerror()
+ {
+ return failonerror;
+ }
+
+ /**
+ * Sets the files to includes.
+ * @param filesList The list of files to include.
+ */
+ public void setIncludes(final String filesList)
+ {
+ this.filesList = filesList;
+ }
+
+ /**
+ * Adds a nested <src> element.
+ * @param srcInfo A nested source element.
+ * @throws BuildException if the SourceInfo doesn't reference a file.
+ */
+ public void addConfiguredSrc(final SourceInfo srcInfo)
+ throws BuildException
+ {
+ if (srcInfo.file == null)
+ {
+ final String message = Messages.getString("vfs.tasks/sync.no-source-file.error");
+ throw new BuildException(message);
+ }
+ srcFiles.add(srcInfo);
+ }
+
+ /**
+ * Executes this task.
+ * @throws BuildException if an error occurs.
+ */
+ @Override
+ public void execute() throws BuildException
+ {
+ // Validate
+ if (destFileUrl == null && destDirUrl == null)
+ {
+ final String message =
+ Messages.getString("vfs.tasks/sync.no-destination.error");
+ logOrDie(message, Project.MSG_WARN);
+ return;
+ }
+
+ if (destFileUrl != null && destDirUrl != null)
+ {
+ final String message =
+ Messages.getString("vfs.tasks/sync.too-many-destinations.error");
+ logOrDie(message, Project.MSG_WARN);
+ return;
+ }
+
+ // Add the files of the includes attribute to the list
+ if (srcDirUrl != null && !srcDirUrl.equals(destDirUrl) && filesList != null && filesList.length() > 0)
+ {
+ if (!srcDirUrl.endsWith("/"))
+ {
+ srcDirUrl += "/";
+ }
+ final StringTokenizer tok = new StringTokenizer(filesList, ", \t\n\r\f", false);
+ while (tok.hasMoreTokens())
+ {
+ String nextFile = tok.nextToken();
+
+ // Basic compatibility with Ant fileset for directories
+ if (nextFile.endsWith("/**"))
+ {
+ nextFile = nextFile.substring(0, nextFile.length() - 2);
+ }
+
+ final SourceInfo src = new SourceInfo();
+ src.setFile(srcDirUrl + nextFile);
+ addConfiguredSrc(src);
+ }
+ }
+
+ if (srcFiles.size() == 0)
+ {
+ final String message = Messages.getString("vfs.tasks/sync.no-source-files.warn");
+ logOrDie(message, Project.MSG_WARN);
+ return;
+ }
+
+ // Perform the sync
+ try
+ {
+ if (destFileUrl != null)
+ {
+ handleSingleFile();
+ }
+ else
+ {
+ handleFiles();
+ }
+ }
+ catch (final BuildException e)
+ {
+ throw e;
+ }
+ catch (final Exception e)
+ {
+ throw new BuildException(e.getMessage(), e);
+ }
+ }
+
+ protected void logOrDie(final String message, final int level)
+ {
+ if (!isFailonerror())
+ {
+ log(message, level);
+ return;
+ }
+ throw new BuildException(message);
+ }
+
+ /**
+ * Copies the source files to the destination.
+ */
+ private void handleFiles() throws Exception
+ {
+ // Locate the destination folder, and make sure it exists
+ final FileObject destFolder = resolveFile(destDirUrl);
+ destFolder.createFolder();
+
+ // Locate the source files, and make sure they exist
+ FileName srcDirName = null;
+ if (srcDirUrl != null)
+ {
+ srcDirName = resolveFile(srcDirUrl).getName();
+ }
+ final ArrayList<FileObject> srcs = new ArrayList<FileObject>();
+ for (int i = 0; i < srcFiles.size(); i++)
+ {
+ // Locate the source file, and make sure it exists
+ final SourceInfo src = srcFiles.get(i);
+ final FileObject srcFile = resolveFile(src.file);
+ if (!srcFile.exists())
+ {
+ final String message =
+ Messages.getString("vfs.tasks/sync.src-file-no-exist.warn", srcFile);
+
+ logOrDie(message, Project.MSG_WARN);
+ }
+ else
+ {
+ srcs.add(srcFile);
+ }
+ }
+
+ // Scan the source files
+ final Set<FileObject> destFiles = new HashSet<FileObject>();
+ for (int i = 0; i < srcs.size(); i++)
+ {
+ final FileObject rootFile = srcs.get(i);
+ final FileName rootName = rootFile.getName();
+
+ if (rootFile.isFile())
+ {
+ // Build the destination file name
+ String relName = null;
+ if (srcDirName == null || !srcDirIsBase)
+ {
+ relName = rootName.getBaseName();
+ }
+ else
+ {
+ relName = srcDirName.getRelativeName(rootName);
+ }
+ final FileObject destFile = destFolder.resolveFile(relName, NameScope.DESCENDENT);
+
+ // Do the copy
+ handleFile(destFiles, rootFile, destFile);
+ }
+ else
+ {
+ // Find matching files
+ // If srcDirIsBase is true, select also the sub-directories
+ final FileObject[] files = rootFile.findFiles(srcDirIsBase
+ ? Selectors.SELECT_ALL : Selectors.SELECT_FILES);
+
+ for (final FileObject srcFile : files)
+ {
+ // Build the destination file name
+ String relName = null;
+ if (srcDirName == null || !srcDirIsBase)
+ {
+ relName = rootName.getRelativeName(srcFile.getName());
+ }
+ else
+ {
+ relName = srcDirName.getRelativeName(srcFile.getName());
+ }
+
+ final FileObject destFile =
+ destFolder.resolveFile(relName, NameScope.DESCENDENT);
+
+ // Do the copy
+ handleFile(destFiles, srcFile, destFile);
+ }
+ }
+ }
+
+ // Scan the destination files for files with no source file
+ if (detectMissingSourceFiles())
+ {
+ final FileObject[] allDestFiles = destFolder.findFiles(Selectors.SELECT_FILES);
+ for (final FileObject destFile : allDestFiles)
+ {
+ if (!destFiles.contains(destFile))
+ {
+ handleMissingSourceFile(destFile);
+ }
+ }
+ }
+ }
+
+ /**
+ * Handles a single file, checking for collisions where more than one
+ * source file maps to the same destination file.
+ */
+ private void handleFile(final Set<FileObject> destFiles,
+ final FileObject srcFile,
+ final FileObject destFile) throws Exception
+
+ {
+ // Check for duplicate source files
+ if (destFiles.contains(destFile))
+ {
+ final String message = Messages.getString("vfs.tasks/sync.duplicate-source-files.warn", destFile);
+ logOrDie(message, Project.MSG_WARN);
+ }
+ else
+ {
+ destFiles.add(destFile);
+ }
+
+ // Handle the file
+ handleFile(srcFile, destFile);
+ }
+
+ /**
+ * Copies a single file.
+ */
+ private void handleSingleFile() throws Exception
+ {
+ // Make sure there is exactly one source file, and that it exists
+ // and is a file.
+ if (srcFiles.size() > 1)
+ {
+ final String message =
+ Messages.getString("vfs.tasks/sync.too-many-source-files.error");
+ logOrDie(message, Project.MSG_WARN);
+ return;
+ }
+ final SourceInfo src = srcFiles.get(0);
+ final FileObject srcFile = resolveFile(src.file);
+ if (!srcFile.isFile())
+ {
+ final String message =
+ Messages.getString("vfs.tasks/sync.source-not-file.error", srcFile);
+ logOrDie(message, Project.MSG_WARN);
+ return;
+ }
+
+ // Locate the destination file
+ final FileObject destFile = resolveFile(destFileUrl);
+
+ // Do the copy
+ handleFile(srcFile, destFile);
+ }
+
+ /**
+ * Handles a single source file.
+ */
+ private void handleFile(final FileObject srcFile,
+ final FileObject destFile)
+ throws Exception
+ {
+ if (!destFile.exists()
+ || srcFile.getContent().getLastModifiedTime() > destFile.getContent().getLastModifiedTime())
+ {
+ // Destination file is out-of-date
+ handleOutOfDateFile(srcFile, destFile);
+ }
+ else
+ {
+ // Destination file is up-to-date
+ handleUpToDateFile(srcFile, destFile);
+ }
+ }
+
+ /**
+ * Handles an out-of-date file.
+ * <p>
+ * This is a file where the destination file
+ * either doesn't exist, or is older than the source file.
+ * <p>
+ * This implementation does nothing.
+ *
+ * @param srcFile The source file.
+ * @param destFile The destination file.
+ * @throws Exception Implementation can throw any Exception.
+ */
+ protected void handleOutOfDateFile(final FileObject srcFile,
+ final FileObject destFile)
+ throws Exception
+ {
+ }
+
+ /**
+ * Handles an up-to-date file.
+ * <p>
+ * This is where the destination file exists and is
+ * newer than the source file.
+ * <p>
+ * This implementation does nothing.
+ *
+ * @param srcFile The source file.
+ * @param destFile The destination file.
+ * @throws Exception Implementation can throw any Exception.
+ */
+ protected void handleUpToDateFile(final FileObject srcFile,
+ final FileObject destFile)
+ throws Exception
+ {
+ }
+
+ /**
+ * Handles a destination for which there is no corresponding source file.
+ * <p>
+ * This implementation does nothing.
+ *
+ * @param destFile The existing destination file.
+ * @throws Exception Implementation can throw any Exception.
+ */
+ protected void handleMissingSourceFile(final FileObject destFile)
+ throws Exception
+ {
+ }
+
+ /**
+ * Check if this task cares about destination files with a missing source
+ * file.
+ * <p>
+ * This implementation returns false.
+ *
+ * @return True if missing file is detected.
+ */
+ protected boolean detectMissingSourceFiles()
+ {
+ return false;
+ }
+
+ /**
+ * Information about a source file.
+ */
+ public static class SourceInfo
+ {
+ private String file;
+
+ public void setFile(final String file)
+ {
+ this.file = file;
+ }
+ }
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/CopyTask.java b/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/CopyTask.java
new file mode 100644
index 0000000..8205195
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/CopyTask.java
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.tasks;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.Selectors;
+
+/**
+ * An Ant task that copies matching files.
+ * <p>
+ * TODO - Copy folders that do not contain files.
+ */
+public class CopyTask
+ extends AbstractSyncTask
+{
+ private boolean overwrite;
+ private boolean preserveLastModified = true;
+
+ /**
+ * Enable/disable overwriting of up-to-date files.
+ * @param overwrite true if the file should be overwritten.
+ */
+ public void setOverwrite(final boolean overwrite)
+ {
+ this.overwrite = overwrite;
+ }
+
+ /**
+ * Enable/disable preserving last modified time of copied files.
+ * @param preserveLastModified true if the last modified time should be preserved.
+ */
+ public void setPreserveLastModified(final boolean preserveLastModified)
+ {
+ this.preserveLastModified = preserveLastModified;
+ }
+
+ /**
+ * @return the current value of overwrite
+ */
+ public boolean isOverwrite()
+ {
+ return overwrite;
+ }
+
+ /**
+ * @return the current value of preserveLastModified
+ */
+ public boolean isPreserveLastModified()
+ {
+ return preserveLastModified;
+ }
+
+ /**
+ * Handles an out-of-date file.
+ * @param srcFile The source FileObject.
+ * @param destFile The destination FileObject.
+ */
+ @Override
+ protected void handleOutOfDateFile(final FileObject srcFile,
+ final FileObject destFile)
+ throws FileSystemException
+ {
+ log("Copying " + srcFile.getPublicURIString() + " to " + destFile.getPublicURIString());
+ destFile.copyFrom(srcFile, Selectors.SELECT_SELF);
+ if (preserveLastModified
+ && srcFile.getFileSystem().hasCapability(Capability.GET_LAST_MODIFIED)
+ && destFile.getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FILE))
+ {
+ final long lastModTime = srcFile.getContent().getLastModifiedTime();
+ destFile.getContent().setLastModifiedTime(lastModTime);
+ }
+ }
+
+ /**
+ * Handles an up-to-date file.
+ * @param srcFile The source FileObject.
+ * @param destFile The destination FileObject.
+ */
+ @Override
+ protected void handleUpToDateFile(final FileObject srcFile,
+ final FileObject destFile)
+ throws FileSystemException
+ {
+ if (overwrite)
+ {
+ // Copy the file anyway
+ handleOutOfDateFile(srcFile, destFile);
+ }
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/DeleteTask.java b/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/DeleteTask.java
new file mode 100644
index 0000000..1483f43
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/DeleteTask.java
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.tasks;
+
+import java.util.StringTokenizer;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.util.Messages;
+import org.apache.tools.ant.BuildException;
+
+/**
+ * An Ant task that deletes matching files.
+ * <p>
+ * TOOD - Allow selector to be specified.
+ */
+public class DeleteTask
+ extends VfsTask
+{
+ private String file;
+ private String srcDirUrl;
+ private String filesList;
+
+ /**
+ * Sets the file/folder to delete.
+ *
+ * @param file The name of the file.
+ */
+ public void setFile(final String file)
+ {
+ this.file = file;
+ }
+
+ /**
+ * Sets the source directory.
+ * @param srcDir The source directory.
+ */
+ public void setSrcDir(final String srcDir)
+ {
+ this.srcDirUrl = srcDir;
+ }
+
+ /**
+ * Sets the files to include.
+ * @param filesList The list of files.
+ */
+ public void setIncludes(final String filesList)
+ {
+ this.filesList = filesList;
+ }
+
+ /**
+ * Executes this task.
+ * @throws BuildException if an error occurs.
+ */
+ @Override
+ public void execute() throws BuildException
+ {
+ if ((file == null && srcDirUrl == null) || (srcDirUrl != null && filesList == null))
+ {
+ final String message = Messages.getString("vfs.tasks/delete.no-source-files.error");
+ throw new BuildException(message);
+ }
+
+ try
+ {
+ if (srcDirUrl != null && filesList != null)
+ {
+ log("Deleting " + filesList + " in the directory " + srcDirUrl);
+ if (!srcDirUrl.endsWith("/"))
+ {
+ srcDirUrl += "/";
+ }
+ final StringTokenizer tok = new StringTokenizer(filesList, ", \t\n\r\f", false);
+ while (tok.hasMoreTokens())
+ {
+ final String nextFile = tok.nextToken();
+ final FileObject srcFile = resolveFile(srcDirUrl + nextFile);
+ srcFile.deleteAll();
+ }
+ }
+ else
+ {
+ final FileObject srcFile = resolveFile(file);
+ log("Deleting " + srcFile.getPublicURIString());
+ srcFile.deleteAll();
+ }
+ }
+ catch (final Exception e)
+ {
+ throw new BuildException(e);
+ }
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/MkdirTask.java b/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/MkdirTask.java
new file mode 100644
index 0000000..58ea20d
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/MkdirTask.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.tasks;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.util.Messages;
+import org.apache.tools.ant.BuildException;
+
+/**
+ * An Ant task that creates a directory.
+ */
+public class MkdirTask
+ extends VfsTask
+{
+ private String dirName;
+
+ /**
+ * Sets the directory to create.
+ *
+ * @param dir The directory name.
+ */
+ public void setDir(final String dir)
+ {
+ dirName = dir;
+ }
+
+ /**
+ * Executes the task.
+ * @throws BuildException if an exception occurs.
+ */
+ @Override
+ public void execute() throws BuildException
+ {
+ if (dirName == null)
+ {
+ final String message = Messages.getString("vfs.tasks/no-directory-specified.error");
+ throw new BuildException(message);
+ }
+
+ try
+ {
+ final FileObject dir = resolveFile(dirName);
+ final String message = Messages.getString("vfs.tasks/mkdir.create-folder.info", dir);
+ log(message);
+ dir.createFolder();
+ }
+ catch (final FileSystemException e)
+ {
+ throw new BuildException(e);
+ }
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/MoveTask.java b/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/MoveTask.java
new file mode 100644
index 0000000..36338e3
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/MoveTask.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.tasks;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.Selectors;
+
+/**
+ * An Ant task that moves matching files.
+ * <p>
+ * TODO - Delete matching folders.
+ */
+public class MoveTask
+ extends CopyTask
+{
+ private boolean tryRename;
+
+ /**
+ * Enable/disable move/rename of file (if possible).
+ * @param tryRename true if the file should be renamed.
+ */
+ public void setTryRename(final boolean tryRename)
+ {
+ this.tryRename = tryRename;
+ }
+
+ /**
+ * Handles a single source file.
+ */
+ @Override
+ protected void handleOutOfDateFile(final FileObject srcFile,
+ final FileObject destFile)
+ throws FileSystemException
+ {
+ if (!tryRename || !srcFile.canRenameTo(destFile))
+ {
+ super.handleOutOfDateFile(srcFile, destFile);
+
+ log("Deleting " + srcFile.getPublicURIString());
+ srcFile.delete(Selectors.SELECT_SELF);
+ }
+ else
+ {
+ log("Rename " + srcFile.getPublicURIString() + " to " + destFile.getPublicURIString());
+ srcFile.moveTo(destFile);
+ if (!isPreserveLastModified()
+ && destFile.getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FILE))
+ {
+ destFile.getContent().setLastModifiedTime(System.currentTimeMillis());
+ }
+ }
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/ShowFileTask.java b/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/ShowFileTask.java
new file mode 100644
index 0000000..db98057
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/ShowFileTask.java
@@ -0,0 +1,164 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.tasks;
+
+import java.io.BufferedReader;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.util.Date;
+
+import org.apache.commons.vfs2.FileContent;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.tools.ant.BuildException;
+
+/**
+ * An Ant task that writes the details of a file to Ant's log.
+ */
+public class ShowFileTask
+ extends VfsTask
+{
+ private static final String INDENT = " ";
+ private String url;
+ private boolean showContent;
+ private boolean recursive;
+
+
+ /**
+ * The URL of the file to display.
+ * @param url The url of the file.
+ */
+ public void setFile(final String url)
+ {
+ this.url = url;
+ }
+
+ /**
+ * Shows the content. Assumes the content is text, encoded using the
+ * platform's default encoding.
+ * @param showContent true if the content should be shown.
+ */
+ public void setShowContent(final boolean showContent)
+ {
+ this.showContent = showContent;
+ }
+
+ /**
+ * Recursively shows the descendants of the file.
+ * @param recursive true if descendants should be shown.
+ */
+ public void setRecursive(final boolean recursive)
+ {
+ this.recursive = recursive;
+ }
+
+ /**
+ * Executes the task.
+ * @throws BuildException if any exception is thrown.
+ */
+ @Override
+ public void execute() throws BuildException
+ {
+ try
+ {
+ final FileObject file = resolveFile(url);
+ log("Details of " + file.getPublicURIString());
+ showFile(file, INDENT);
+ }
+ catch (final Exception e)
+ {
+ throw new BuildException(e);
+ }
+ }
+
+ /**
+ * Logs the details of a file.
+ */
+ private void showFile(final FileObject file, final String prefix) throws Exception
+ {
+ // Write details
+ final StringBuilder msg = new StringBuilder(prefix);
+ msg.append(file.getName().getBaseName());
+ if (file.exists())
+ {
+ msg.append(" (");
+ msg.append(file.getType().getName());
+ msg.append(")");
+ }
+ else
+ {
+ msg.append(" (unknown)");
+ }
+ log(msg.toString());
+
+ if (file.exists())
+ {
+ final String newPrefix = prefix + INDENT;
+ if (file.getType().hasContent())
+ {
+ final FileContent content = file.getContent();
+ log(newPrefix + "Content-Length: " + content.getSize());
+ log(newPrefix + "Last-Modified" + new Date(content.getLastModifiedTime()));
+ if (showContent)
+ {
+ log(newPrefix + "Content:");
+ logContent(file, newPrefix);
+ }
+ }
+ if (file.getType().hasChildren())
+ {
+ final FileObject[] children = file.getChildren();
+ for (final FileObject child : children)
+ {
+ if (recursive)
+ {
+ showFile(child, newPrefix);
+ }
+ else
+ {
+ log(newPrefix + child.getName().getBaseName());
+ }
+ }
+ }
+ }
+ }
+
+ /**
+ * Writes the content of the file to Ant log.
+ */
+ private void logContent(final FileObject file, final String prefix)
+ throws Exception
+ {
+ final InputStream instr = file.getContent().getInputStream();
+ try
+ {
+ final BufferedReader reader = new BufferedReader(new InputStreamReader(instr));
+ while (true)
+ {
+ final String line = reader.readLine();
+ if (line == null)
+ {
+ break;
+ }
+ log(prefix + line);
+ }
+ }
+ finally
+ {
+ instr.close();
+ }
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/SyncTask.java b/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/SyncTask.java
new file mode 100644
index 0000000..7e324f6
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/SyncTask.java
@@ -0,0 +1,48 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.tasks;
+
+import org.apache.commons.vfs2.FileObject;
+
+/**
+ * A task that synchronises the destination folder to look exactly like
+ * the source folder (or folders).
+ */
+public class SyncTask
+ extends CopyTask
+{
+ /**
+ * Handles a destination for which there is no corresponding source file.
+ */
+ @Override
+ protected void handleMissingSourceFile(final FileObject destFile)
+ throws Exception
+ {
+ log("deleting " + destFile.getPublicURIString());
+ //destFile.delete( Selectors.SELECT_SELF );
+ }
+
+ /**
+ * Check if this task cares about destination files with a missing source
+ * file.
+ */
+ @Override
+ protected boolean detectMissingSourceFiles()
+ {
+ return true;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/VfsTask.java b/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/VfsTask.java
new file mode 100644
index 0000000..2247d37
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/VfsTask.java
@@ -0,0 +1,237 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.tasks;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.impl.StandardFileSystemManager;
+import org.apache.tools.ant.BuildEvent;
+import org.apache.tools.ant.Project;
+import org.apache.tools.ant.SubBuildListener;
+import org.apache.tools.ant.Task;
+
+/**
+ * Base class for the VFS Ant tasks. Takes care of creating a FileSystemManager,
+ * and for cleaning it up at the end of the build. Also provides some
+ * utility methods.
+ */
+public class VfsTask
+ extends Task
+{
+ private static StandardFileSystemManager manager;
+
+ /**
+ * Resolves a URI to a file, relative to the project's base directory.
+ *
+ * @param uri The URI to resolve.
+ * @return resolved file object.
+ * @throws FileSystemException If an error occurred.
+ */
+ protected FileObject resolveFile(final String uri)
+ throws FileSystemException
+ {
+ if (manager == null)
+ {
+ final StandardFileSystemManager mngr = new StandardFileSystemManager();
+ mngr.setLogger(new AntLogger());
+ mngr.init();
+ manager = mngr;
+ getProject().addBuildListener(new CloseListener());
+ }
+ return manager.resolveFile(getProject().getBaseDir(), uri);
+ }
+
+ /**
+ * Close the manager
+ */
+ protected void closeManager()
+ {
+ if (manager != null)
+ {
+ manager.close();
+ manager = null;
+ }
+ }
+
+ /**
+ * Closes the VFS manager when the project finishes.
+ */
+ private class CloseListener
+ implements SubBuildListener
+ {
+ @Override
+ public void subBuildStarted(final BuildEvent buildEvent)
+ {
+ }
+
+ @Override
+ public void subBuildFinished(final BuildEvent buildEvent)
+ {
+ closeManager();
+ }
+
+ @Override
+ public void buildFinished(final BuildEvent event)
+ {
+ closeManager();
+ }
+
+ @Override
+ public void buildStarted(final BuildEvent event)
+ {
+ }
+
+ @Override
+ public void messageLogged(final BuildEvent event)
+ {
+ }
+
+ @Override
+ public void targetFinished(final BuildEvent event)
+ {
+ }
+
+ @Override
+ public void targetStarted(final BuildEvent event)
+ {
+ }
+
+ @Override
+ public void taskFinished(final BuildEvent event)
+ {
+ }
+
+ @Override
+ public void taskStarted(final BuildEvent event)
+ {
+ }
+ }
+
+ /**
+ * A commons-logging wrapper for Ant logging.
+ */
+ private class AntLogger
+ implements Log
+ {
+ @Override
+ public void debug(final Object o)
+ {
+ log(String.valueOf(o), Project.MSG_DEBUG);
+ }
+
+ @Override
+ public void debug(final Object o, final Throwable throwable)
+ {
+ debug(o);
+ }
+
+ @Override
+ public void error(final Object o)
+ {
+ log(String.valueOf(o), Project.MSG_ERR);
+ }
+
+ @Override
+ public void error(final Object o, final Throwable throwable)
+ {
+ error(o);
+ }
+
+ @Override
+ public void fatal(final Object o)
+ {
+ log(String.valueOf(o), Project.MSG_ERR);
+ }
+
+ @Override
+ public void fatal(final Object o, final Throwable throwable)
+ {
+ fatal(o);
+ }
+
+ @Override
+ public void info(final Object o)
+ {
+ log(String.valueOf(o), Project.MSG_INFO);
+ }
+
+ @Override
+ public void info(final Object o, final Throwable throwable)
+ {
+ info(o);
+ }
+
+ @Override
+ public void trace(final Object o)
+ {
+ }
+
+ @Override
+ public void trace(final Object o, final Throwable throwable)
+ {
+ }
+
+ @Override
+ public void warn(final Object o)
+ {
+ log(String.valueOf(o), Project.MSG_WARN);
+ }
+
+ @Override
+ public void warn(final Object o, final Throwable throwable)
+ {
+ warn(o);
+ }
+
+ @Override
+ public boolean isDebugEnabled()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean isErrorEnabled()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean isFatalEnabled()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean isInfoEnabled()
+ {
+ return true;
+ }
+
+ @Override
+ public boolean isTraceEnabled()
+ {
+ return false;
+ }
+
+ @Override
+ public boolean isWarnEnabled()
+ {
+ return true;
+ }
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/antlib.xml b/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/antlib.xml
new file mode 100644
index 0000000..1d79d26
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/antlib.xml
@@ -0,0 +1,24 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<antlib>
+ <taskdef name="copy" classname="org.apache.commons.vfs2.tasks.CopyTask" onerror="report"/>
+ <taskdef name="delete" classname="org.apache.commons.vfs2.tasks.DeleteTask" onerror="report"/>
+ <taskdef name="mkdir" classname="org.apache.commons.vfs2.tasks.MkdirTask" onerror="report"/>
+ <taskdef name="move" classname="org.apache.commons.vfs2.tasks.MoveTask" onerror="report"/>
+ <taskdef name="show-file" classname="org.apache.commons.vfs2.tasks.ShowFileTask" onerror="report"/>
+ <taskdef name="sync" classname="org.apache.commons.vfs2.tasks.SyncTask" onerror="report"/>
+</antlib>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/package.html
new file mode 100644
index 0000000..d1dcd7d
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>The VFS Ant Tasks.</p>
+</body>
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/tasks.properties b/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/tasks.properties
new file mode 100644
index 0000000..4210c79
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/tasks/tasks.properties
@@ -0,0 +1,21 @@
+# Licensed to the Apache Software Foundation (ASF) under one or more
+# contributor license agreements. See the NOTICE file distributed with
+# this work for additional information regarding copyright ownership.
+# The ASF licenses this file to You under the Apache License, Version 2.0
+# (the "License"); you may not use this file except in compliance with
+# the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+v-copy=org.apache.commons.vfs2.tasks.CopyTask
+v-move=org.apache.commons.vfs2.tasks.MoveTask
+v-sync=org.apache.commons.vfs2.tasks.SyncTask
+v-delete=org.apache.commons.vfs2.tasks.DeleteTask
+v-mkdir=org.apache.commons.vfs2.tasks.MkdirTask
+v-show-file=org.apache.commons.vfs2.tasks.ShowFileTask
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/util/CombinedResources.java b/trunk/core/src/main/java/org/apache/commons/vfs2/util/CombinedResources.java
new file mode 100644
index 0000000..a054825
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/util/CombinedResources.java
@@ -0,0 +1,149 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.util;
+
+import java.io.IOException;
+import java.net.URL;
+import java.util.Enumeration;
+import java.util.Locale;
+import java.util.Properties;
+import java.util.ResourceBundle;
+
+/**
+ * @since 2.0
+ */
+public class CombinedResources extends ResourceBundle
+{
+ // locale.getLanguage()
+ // locale.getCountry()
+ // locale.getVariant()
+
+ private final String resourceName;
+ private boolean inited;
+ private final Properties properties = new Properties();
+
+ public CombinedResources(final String resourceName)
+ {
+ this.resourceName = resourceName;
+ }
+
+ protected void init()
+ {
+ if (inited)
+ {
+ return;
+ }
+
+ loadResources(getResourceName());
+ loadResources(Locale.getDefault());
+ loadResources(getLocale());
+ inited = true;
+ }
+
+ protected void loadResources(final Locale locale)
+ {
+ if (locale == null)
+ {
+ return;
+ }
+ final String[] parts = new String[]{locale.getLanguage(), locale.getCountry(), locale.getVariant()};
+ final StringBuilder sb = new StringBuilder();
+ for (int i = 0; i < 3; i++)
+ {
+ sb.append(getResourceName());
+ for (int j = 0; j < i; j++)
+ {
+ sb.append('_').append(parts[j]);
+ }
+ if (parts[i].length() != 0)
+ {
+ sb.append('_').append(parts[i]);
+ loadResources(sb.toString());
+ }
+ sb.setLength(0);
+ }
+ }
+
+ protected void loadResources(String resourceName)
+ {
+ ClassLoader loader = getClass().getClassLoader();
+ if (loader == null)
+ {
+ loader = ClassLoader.getSystemClassLoader();
+ }
+ resourceName = resourceName.replace('.', '/') + ".properties";
+ try
+ {
+ final Enumeration<URL> resources = loader.getResources(resourceName);
+ while (resources.hasMoreElements())
+ {
+ final URL resource = resources.nextElement();
+ try
+ {
+ properties.load(resource.openConnection().getInputStream());
+ }
+ catch (final IOException ignored)
+ {
+ /* Ignored. */
+ }
+ }
+ }
+ catch (final IOException ignored)
+ {
+ /* Ignored. */
+ }
+ }
+
+ public String getResourceName()
+ {
+ return resourceName;
+ }
+
+ @Override
+ public Enumeration<String> getKeys()
+ {
+ if (!inited)
+ {
+ init();
+ }
+ return new Enumeration<String>()
+ {
+ @Override
+ public boolean hasMoreElements()
+ {
+ return properties.keys().hasMoreElements();
+ }
+ @Override
+ public String nextElement()
+ {
+ // We know that our properties will only ever contain Strings
+ return (String) properties.keys().nextElement();
+ }
+
+ };
+ }
+
+ @Override
+ protected Object handleGetObject(final String key)
+ {
+ if (!inited)
+ {
+ init();
+ }
+ return properties.get(key);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/util/Cryptor.java b/trunk/core/src/main/java/org/apache/commons/vfs2/util/Cryptor.java
new file mode 100644
index 0000000..d976c80
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/util/Cryptor.java
@@ -0,0 +1,39 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.util;
+
+/**
+ * @since 2.0
+ */
+public interface Cryptor
+{
+ /**
+ * Encrypt the plain text password.
+ * @param plainKey The password.
+ * @return The encrypted password String.
+ * @throws Exception If an error occurs.
+ */
+ String encrypt(String plainKey) throws Exception;
+
+ /**
+ * Decrypts the password.
+ * @param encryptedKey the encrypted password.
+ * @return The plain text password.
+ * @throws Exception If an error occurs.
+ */
+ String decrypt(String encryptedKey) throws Exception;
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/util/CryptorFactory.java b/trunk/core/src/main/java/org/apache/commons/vfs2/util/CryptorFactory.java
new file mode 100644
index 0000000..08fe7f3
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/util/CryptorFactory.java
@@ -0,0 +1,79 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.util;
+
+/**
+ * Factory to create an instance of a Cryptor.
+ * @since 2.0
+ */
+public final class CryptorFactory
+{
+ /**
+ * The System property name to identify the Cryptor class to be used.
+ */
+ public static final String CRYPTOR_CLASS = "org.apache.commons.vfs2.cryptor";
+
+ private static Cryptor instance;
+
+ /**
+ * Prevent instantiation of the class.
+ */
+ private CryptorFactory()
+ {
+
+ }
+
+ /**
+ * Allows the Cryptor class to be set programmatically.
+ * @param cryptor The Cryptor.
+ */
+ public static synchronized void setCryptor(final Cryptor cryptor)
+ {
+ instance = cryptor;
+ }
+
+ /**
+ * Return the Cryptor. If one has not been previously set, create it. The Cryptor class
+ * can be set by setting the "org.apache.commons.vfs2.cryptor" System property to the
+ * name of the Cryptor class.
+ * @return The Cryptor.
+ */
+ public static synchronized Cryptor getCryptor()
+ {
+ if (instance != null)
+ {
+ return instance;
+ }
+
+ final String cryptorClass = System.getProperty(CRYPTOR_CLASS);
+ if (cryptorClass != null)
+ {
+ try
+ {
+ final Class<?> clazz = Class.forName(cryptorClass);
+ instance = (Cryptor) clazz.newInstance();
+ return instance;
+ }
+ catch (final Exception ex)
+ {
+ throw new RuntimeException("Unable to create Cryptor " + cryptorClass, ex);
+ }
+ }
+ instance = new DefaultCryptor();
+ return instance;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/util/DefaultCryptor.java b/trunk/core/src/main/java/org/apache/commons/vfs2/util/DefaultCryptor.java
new file mode 100644
index 0000000..8ea5a62
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/util/DefaultCryptor.java
@@ -0,0 +1,144 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.util;
+
+import javax.crypto.Cipher;
+import javax.crypto.spec.SecretKeySpec;
+
+/**
+ * Allows passwords to be encrypted and decrypted.
+ * <p>
+ * Warning: This uses AES128 with a fixed encryption key.
+ * This is only an obfuscation no cryptographic secure protection.
+ *
+ * @since 2.0
+ */
+public class DefaultCryptor implements Cryptor
+{
+ private static final char[] HEX_CHARS =
+ {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
+
+ private static final byte[] KEY_BYTES = {0x41, 0x70, 0x61, 0x63, 0x68, 0x65, 0x43, 0x6F, 0x6D, 0x6D,
+ 0x6F, 0x6E, 0x73, 0x56, 0x46, 0x53};
+
+ private static final int INDEX_NOT_FOUND = -1;
+
+ private static final int BITS_IN_HALF_BYTE = 4;
+
+ private static final char MASK = 0x0f;
+
+ /**
+ * Encrypt the plain text password.
+ * <p>
+ * Warning: This uses AES128 with a fixed encryption key.
+ * This is only an obfuscation no cryptographic secure protection.
+ *
+ * @param plainKey The password.
+ * @return The encrypted password String.
+ * @throws Exception If an error occurs.
+ */
+ @Override
+ public String encrypt(final String plainKey) throws Exception
+ {
+ final byte[] input = plainKey.getBytes();
+ final SecretKeySpec key = new SecretKeySpec(KEY_BYTES, "AES");
+
+ final Cipher cipher = Cipher.getInstance("AES");
+
+ // encryption pass
+ cipher.init(Cipher.ENCRYPT_MODE, key);
+
+ final byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
+ int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
+ ctLength += cipher.doFinal(cipherText, ctLength);
+ return encode(cipherText);
+ }
+
+ /**
+ * Decrypts the password.
+ * @param encryptedKey the encrypted password.
+ * @return The plain text password.
+ * @throws Exception If an error occurs.
+ */
+ @Override
+ public String decrypt(final String encryptedKey) throws Exception
+ {
+ final SecretKeySpec key = new SecretKeySpec(KEY_BYTES, "AES");
+ final Cipher cipher = Cipher.getInstance("AES");
+ cipher.init(Cipher.DECRYPT_MODE, key);
+ final byte[] decoded = decode(encryptedKey);
+ final byte[] plainText = new byte[cipher.getOutputSize(decoded.length)];
+ int ptLength = cipher.update(decoded, 0, decoded.length, plainText, 0);
+ ptLength += cipher.doFinal(plainText, ptLength);
+ return new String(plainText).substring(0, ptLength);
+ }
+
+ /** Hex-encode bytes. */
+ private String encode(final byte[] bytes)
+ {
+ final StringBuilder builder = new StringBuilder();
+
+ for (final byte b : bytes)
+ {
+ builder.append(HEX_CHARS[(b >> BITS_IN_HALF_BYTE) & MASK]);
+ builder.append(HEX_CHARS[b & MASK]);
+ }
+ return builder.toString();
+ }
+
+ /** Decodes Hey-Bytes. */
+ private byte[] decode(final String str)
+ {
+ final int length = str.length() / 2;
+ final byte[] decoded = new byte[length];
+ final char[] chars = str.toCharArray();
+ int index = 0;
+ for (int i = 0; i < chars.length; ++i)
+ {
+ final int id1 = indexOf(HEX_CHARS, chars[i]);
+ if (id1 == -1)
+ {
+ throw new IllegalArgumentException("Character " + chars[i] + " at position " + i
+ + " is not a valid hexidecimal character");
+ }
+ final int id2 = indexOf(HEX_CHARS, chars[++i]);
+ if (id2 == -1)
+ {
+ throw new IllegalArgumentException("Character " + chars[i] + " at position " + i
+ + " is not a valid hexidecimal character");
+ }
+ decoded[index++] = (byte) ((id1 << BITS_IN_HALF_BYTE) | id2);
+ }
+ return decoded;
+ }
+
+ private int indexOf(final char[] array, final char valueToFind)
+ {
+ if (array == null)
+ {
+ return INDEX_NOT_FOUND;
+ }
+ for (int i = 0; i < array.length; i++)
+ {
+ if (valueToFind == array[i])
+ {
+ return i;
+ }
+ }
+ return INDEX_NOT_FOUND;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/util/DelegatingFileSystemOptionsBuilder.java b/trunk/core/src/main/java/org/apache/commons/vfs2/util/DelegatingFileSystemOptionsBuilder.java
new file mode 100644
index 0000000..a13711e
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/util/DelegatingFileSystemOptionsBuilder.java
@@ -0,0 +1,471 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.util;
+
+import java.lang.reflect.Array;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.TreeMap;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.vfs2.FileSystemConfigBuilder;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FileSystemOptions;
+
+/**
+ * This class use reflection to set a configuration value using the fileSystemConfigBuilder
+ * associated the a scheme.<br><br>
+ * Example:<br>
+ * <pre>
+ * FileSystemOptions fso = new FileSystemOptions();
+ * DelegatingFileSystemOptionsBuilder delegate = new DelegatingFileSystemOptionsBuilder(VFS.getManager());
+ * delegate.setConfigString(fso, "sftp", "identities", "c:/tmp/test.ident");
+ * delegate.setConfigString(fso, "http", "proxyPort", "8080");
+ * delegate.setConfigClass(fso, "sftp", "userinfo", TrustEveryoneUserInfo.class);
+ * </pre>
+ */
+public class DelegatingFileSystemOptionsBuilder
+{
+ @SuppressWarnings("unchecked") // OK, it is a String
+ private static final Class<String>[] STRING_PARAM = new Class[]{String.class};
+ private static final Map<String, Class<?>> PRIMATIVE_TO_OBJECT = new TreeMap<String, Class<?>>();
+ private static final Log log = LogFactory.getLog(DelegatingFileSystemOptionsBuilder.class);
+
+ private final FileSystemManager manager;
+ private final Map<String, Map<String, List<Method>>> beanMethods = new TreeMap<String, Map<String, List<Method>>>();
+
+ static
+ {
+ PRIMATIVE_TO_OBJECT.put(Void.TYPE.getName(), Void.class);
+ PRIMATIVE_TO_OBJECT.put(Boolean.TYPE.getName(), Boolean.class);
+ PRIMATIVE_TO_OBJECT.put(Byte.TYPE.getName(), Byte.class);
+ PRIMATIVE_TO_OBJECT.put(Character.TYPE.getName(), Character.class);
+ PRIMATIVE_TO_OBJECT.put(Short.TYPE.getName(), Short.class);
+ PRIMATIVE_TO_OBJECT.put(Integer.TYPE.getName(), Integer.class);
+ PRIMATIVE_TO_OBJECT.put(Long.TYPE.getName(), Long.class);
+ PRIMATIVE_TO_OBJECT.put(Double.TYPE.getName(), Double.class);
+ PRIMATIVE_TO_OBJECT.put(Float.TYPE.getName(), Float.class);
+ }
+
+ /**
+ * Context.
+ */
+ private static final class Context
+ {
+ private final FileSystemOptions fso;
+ private final String scheme;
+ private final String name;
+ private final Object[] values;
+
+ private List<Method> configSetters;
+ private FileSystemConfigBuilder fileSystemConfigBuilder;
+
+ private Context(final FileSystemOptions fso, final String scheme, final String name, final Object[] values)
+ {
+ this.fso = fso;
+ this.scheme = scheme;
+ this.name = name;
+ this.values = values;
+ }
+ }
+
+ /**
+ * Constructor.<br>
+ * Pass in your fileSystemManager instance.
+ *
+ * @param manager the manager to use to get the fileSystemConfigBuilder assocated to a scheme
+ */
+ public DelegatingFileSystemOptionsBuilder(final FileSystemManager manager)
+ {
+ this.manager = manager;
+ }
+
+ protected FileSystemManager getManager()
+ {
+ return manager;
+ }
+
+ /**
+ * Set a single string value.
+ *
+ * @param fso FileSystemOptions
+ * @param scheme scheme
+ * @param name name
+ * @param value value
+ * @throws FileSystemException if an error occurs.
+ */
+ public void setConfigString(final FileSystemOptions fso, final String scheme, final String name,
+ final String value) throws FileSystemException
+ {
+ setConfigStrings(fso, scheme, name, new String[]{value});
+ }
+
+ /**
+ * Set an array of string value.
+ *
+ * @param fso FileSystemOptions
+ * @param scheme scheme
+ * @param name name
+ * @param values values
+ * @throws FileSystemException if an error occurs.
+ */
+ public void setConfigStrings(final FileSystemOptions fso, final String scheme, final String name,
+ final String[] values) throws FileSystemException
+ {
+ final Context ctx = new Context(fso, scheme, name, values);
+
+ setValues(ctx);
+ }
+
+ /**
+ * Set a single class value.<br>
+ * The class has to implement a no-args constructor, else the instantiation might fail.
+ *
+ * @param fso FileSystemOptions
+ * @param scheme scheme
+ * @param name name
+ * @param className className
+ * @throws FileSystemException if an error occurs.
+ * @throws IllegalAccessException if a class canoot be accessed.
+ * @throws InstantiationException if a class cannot be instantiated.
+ */
+ public void setConfigClass(final FileSystemOptions fso, final String scheme, final String name,
+ final Class<?> className)
+ throws FileSystemException, IllegalAccessException, InstantiationException
+ {
+ setConfigClasses(fso, scheme, name, new Class[]{className});
+ }
+
+ /**
+ * Set an array of class values.<br>
+ * The class has to implement a no-args constructor, else the instantiation might fail.
+ *
+ * @param fso FileSystemOptions
+ * @param scheme scheme
+ * @param name name
+ * @param classNames classNames
+ * @throws FileSystemException if an error occurs.
+ * @throws IllegalAccessException if a class canoot be accessed.
+ * @throws InstantiationException if a class cannot be instantiated.
+ */
+ public void setConfigClasses(final FileSystemOptions fso, final String scheme, final String name,
+ final Class<?>[] classNames)
+ throws FileSystemException, IllegalAccessException, InstantiationException
+ {
+ final Object[] values = new Object[classNames.length];
+ for (int iterClassNames = 0; iterClassNames < values.length; iterClassNames++)
+ {
+ values[iterClassNames] = classNames[iterClassNames].newInstance();
+ }
+
+ final Context ctx = new Context(fso, scheme, name, values);
+
+ setValues(ctx);
+ }
+
+ /**
+ * sets the values using the informations of the given context.<br>
+ */
+ private void setValues(final Context ctx) throws FileSystemException
+ {
+ // find all setter methods suitable for the given "name"
+ if (!fillConfigSetters(ctx))
+ {
+ throw new FileSystemException("vfs.provider/config-key-invalid.error",
+ ctx.scheme,
+ ctx.name);
+ }
+
+ // get the fileSystemConfigBuilder
+ ctx.fileSystemConfigBuilder = getManager().getFileSystemConfigBuilder(ctx.scheme);
+
+ // try to find a setter which could accept the value
+ final Iterator<Method> iterConfigSetters = ctx.configSetters.iterator();
+ while (iterConfigSetters.hasNext())
+ {
+ final Method configSetter = iterConfigSetters.next();
+ if (convertValuesAndInvoke(configSetter, ctx))
+ {
+ return;
+ }
+ }
+
+ throw new FileSystemException("vfs.provider/config-value-invalid.error",
+ ctx.scheme,
+ ctx.name,
+ ctx.values);
+ }
+
+ /**
+ * tries to convert the value and pass it to the given method
+ */
+ private boolean convertValuesAndInvoke(final Method configSetter, final Context ctx) throws FileSystemException
+ {
+ final Class<?>[] parameters = configSetter.getParameterTypes();
+ if (parameters.length < 2)
+ {
+ return false;
+ }
+ if (!parameters[0].isAssignableFrom(FileSystemOptions.class))
+ {
+ return false;
+ }
+
+ final Class<?> valueParameter = parameters[1];
+ Class<?> type;
+ if (valueParameter.isArray())
+ {
+ type = valueParameter.getComponentType();
+ }
+ else
+ {
+ if (ctx.values.length > 1)
+ {
+ return false;
+ }
+
+ type = valueParameter;
+ }
+
+ if (type.isPrimitive())
+ {
+ final Class<?> objectType = PRIMATIVE_TO_OBJECT.get(type.getName());
+ if (objectType == null)
+ {
+ log.warn(Messages.getString("vfs.provider/config-unexpected-primitive.error", type.getName()));
+ return false;
+ }
+ type = objectType;
+ }
+
+ final Class<? extends Object> valueClass = ctx.values[0].getClass();
+ if (type.isAssignableFrom(valueClass))
+ {
+ // can set value directly
+ invokeSetter(valueParameter, ctx, configSetter, ctx.values);
+ return true;
+ }
+ if (valueClass != String.class)
+ {
+ log.warn(Messages.getString("vfs.provider/config-unexpected-value-class.error",
+ valueClass.getName(),
+ ctx.scheme,
+ ctx.name
+ ));
+ return false;
+ }
+
+ final Object convertedValues = Array.newInstance(type, ctx.values.length);
+
+ Constructor<?> valueConstructor;
+ try
+ {
+ valueConstructor = type.getConstructor(STRING_PARAM);
+ }
+ catch (final NoSuchMethodException e)
+ {
+ valueConstructor = null;
+ }
+ if (valueConstructor != null)
+ {
+ // can convert using constructor
+ for (int iterValues = 0; iterValues < ctx.values.length; iterValues++)
+ {
+ try
+ {
+ Array.set(convertedValues, iterValues,
+ valueConstructor.newInstance(new Object[]{ctx.values[iterValues]}));
+ }
+ catch (final InstantiationException e)
+ {
+ throw new FileSystemException(e);
+ }
+ catch (final IllegalAccessException e)
+ {
+ throw new FileSystemException(e);
+ }
+ catch (final InvocationTargetException e)
+ {
+ throw new FileSystemException(e);
+ }
+ }
+
+ invokeSetter(valueParameter, ctx, configSetter, convertedValues);
+ return true;
+ }
+
+ Method valueFactory;
+ try
+ {
+ valueFactory = type.getMethod("valueOf", STRING_PARAM);
+ if (!Modifier.isStatic(valueFactory.getModifiers()))
+ {
+ valueFactory = null;
+ }
+ }
+ catch (final NoSuchMethodException e)
+ {
+ valueFactory = null;
+ }
+
+ if (valueFactory != null)
+ {
+ // can convert using factory method (valueOf)
+ for (int iterValues = 0; iterValues < ctx.values.length; iterValues++)
+ {
+ try
+ {
+ Array.set(convertedValues, iterValues,
+ valueFactory.invoke(null, new Object[]{ctx.values[iterValues]}));
+ }
+ catch (final IllegalAccessException e)
+ {
+ throw new FileSystemException(e);
+ }
+ catch (final InvocationTargetException e)
+ {
+ throw new FileSystemException(e);
+ }
+ }
+
+ invokeSetter(valueParameter, ctx, configSetter, convertedValues);
+ return true;
+ }
+
+ return false;
+ }
+
+ /**
+ * invokes the method with the converted values
+ */
+ private void invokeSetter(final Class<?> valueParameter, final Context ctx, final Method configSetter,
+ final Object values)
+ throws FileSystemException
+ {
+ Object[] args;
+ if (valueParameter.isArray())
+ {
+ args = new Object[]
+ {
+ ctx.fso,
+ values
+ };
+ }
+ else
+ {
+ args = new Object[]
+ {
+ ctx.fso,
+ Array.get(values, 0)
+ };
+ }
+ try
+ {
+ configSetter.invoke(ctx.fileSystemConfigBuilder, args);
+ }
+ catch (final IllegalAccessException e)
+ {
+ throw new FileSystemException(e);
+ }
+ catch (final InvocationTargetException e)
+ {
+ throw new FileSystemException(e);
+ }
+ }
+
+ /**
+ * fills all available set*() methods for the context-scheme into the context.
+ */
+ private boolean fillConfigSetters(final Context ctx)
+ throws FileSystemException
+ {
+ final Map<String, List<Method>> schemeMethods = getSchemeMethods(ctx.scheme);
+ final List<Method> configSetters = schemeMethods.get(ctx.name.toLowerCase());
+ if (configSetters == null)
+ {
+ return false;
+ }
+
+ ctx.configSetters = configSetters;
+ return true;
+ }
+
+ /**
+ * get (cached) list of set*() methods for the given scheme
+ */
+ private Map<String, List<Method>> getSchemeMethods(final String scheme) throws FileSystemException
+ {
+ Map<String, List<Method>> schemeMethods = beanMethods.get(scheme);
+ if (schemeMethods == null)
+ {
+ schemeMethods = createSchemeMethods(scheme);
+ beanMethods.put(scheme, schemeMethods);
+ }
+
+ return schemeMethods;
+ }
+
+ /**
+ * create the list of all set*() methods for the given scheme
+ */
+ private Map<String, List<Method>> createSchemeMethods(final String scheme) throws FileSystemException
+ {
+ final FileSystemConfigBuilder fscb = getManager().getFileSystemConfigBuilder(scheme);
+ if (fscb == null)
+ {
+ throw new FileSystemException("vfs.provider/no-config-builder.error", scheme);
+ }
+
+ final Map<String, List<Method>> schemeMethods = new TreeMap<String, List<Method>>();
+
+ final Method[] methods = fscb.getClass().getMethods();
+ for (final Method method : methods)
+ {
+ if (!Modifier.isPublic(method.getModifiers()))
+ {
+ continue;
+ }
+
+ final String methodName = method.getName();
+ if (!methodName.startsWith("set"))
+ {
+ // not a setter
+ continue;
+ }
+
+ final String key = methodName.substring(3).toLowerCase();
+
+ List<Method> configSetter = schemeMethods.get(key);
+ if (configSetter == null)
+ {
+ configSetter = new ArrayList<Method>(2);
+ schemeMethods.put(key, configSetter);
+ }
+ configSetter.add(method);
+ }
+
+ return schemeMethods;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/util/EncryptUtil.java b/trunk/core/src/main/java/org/apache/commons/vfs2/util/EncryptUtil.java
new file mode 100644
index 0000000..6816e6c
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/util/EncryptUtil.java
@@ -0,0 +1,54 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.util;
+
+/**
+ * Allows passwords to be encrypted and decrypted.
+ * @since 2.0
+ */
+public final class EncryptUtil
+{
+ /**
+ * Don't allow class instantiation.
+ */
+ private EncryptUtil()
+ {
+ }
+
+ /**
+ * This class can be called with "encrypt" password as the arguments where encrypt is
+ * a literal and password is replaced with the clear text password to be encrypted.
+ *
+ * @param args The arguments in the form "command" parm1, parm2.
+ * @throws Exception If an error occurs.
+ */
+ public static void main(final String[] args) throws Exception
+ {
+ if (args.length != 2 || !args[0].equals("encrypt"))
+ {
+ System.err.println("Usage: \"EncryptUtil encrypt\" password");
+ System.err.println(" password : The clear text password to encrypt");
+ System.exit(0);
+ }
+ final Cryptor cryptor = CryptorFactory.getCryptor();
+
+ if (args[0].equals("encrypt"))
+ {
+ System.out.println(cryptor.encrypt(args[1]));
+ }
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/util/FileObjectUtils.java b/trunk/core/src/main/java/org/apache/commons/vfs2/util/FileObjectUtils.java
new file mode 100644
index 0000000..ea3a1f6
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/util/FileObjectUtils.java
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.util;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.impl.DecoratedFileObject;
+import org.apache.commons.vfs2.provider.AbstractFileObject;
+
+/**
+ * Stuff to get some strange things from an FileObject.
+ */
+public final class FileObjectUtils
+{
+ private FileObjectUtils()
+ {
+ }
+
+ /**
+ * Get access to the base object even if decorated.
+ * @param fileObject The FileObject.
+ * @return The decorated FileObject or null.
+ * @throws FileSystemException if an error occurs.
+ */
+ public static AbstractFileObject getAbstractFileObject(final FileObject fileObject) throws FileSystemException
+ {
+ Object searchObject = fileObject;
+ while (searchObject instanceof DecoratedFileObject)
+ {
+ searchObject = ((DecoratedFileObject) searchObject).getDecoratedFileObject();
+ }
+ if (searchObject instanceof AbstractFileObject)
+ {
+ return (AbstractFileObject) searchObject;
+ }
+ if (searchObject == null)
+ {
+ return null;
+ }
+
+ throw new FileSystemException("vfs.util/find-abstract-file-object.error",
+ fileObject == null ? "null" : fileObject.getClass().getName());
+ }
+
+ /**
+ * Check if the given FileObject is instance of given class argument.
+ * @param fileObject The FileObject.
+ * @param wantedClass The Class to check.
+ * @return true if fileObject is an instance of the specified Class.
+ * @throws FileSystemException if an error occurs.
+ */
+ public static boolean isInstanceOf(final FileObject fileObject, final Class<?> wantedClass)
+ throws FileSystemException
+ {
+ Object searchObject = fileObject;
+ while (searchObject instanceof DecoratedFileObject)
+ {
+ if (wantedClass.isInstance(searchObject))
+ {
+ return true;
+ }
+
+ searchObject = ((DecoratedFileObject) searchObject).getDecoratedFileObject();
+ }
+
+ if (wantedClass.isInstance(searchObject))
+ {
+ return true;
+ }
+
+ return false;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/util/Messages.java b/trunk/core/src/main/java/org/apache/commons/vfs2/util/Messages.java
new file mode 100644
index 0000000..d48e8c4
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/util/Messages.java
@@ -0,0 +1,111 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.util;
+
+import java.text.MessageFormat;
+import java.util.MissingResourceException;
+import java.util.ResourceBundle;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ConcurrentMap;
+
+/**
+ * Formats messages.
+ */
+public final class Messages
+{
+ /**
+ * Map from message code to MessageFormat object for the message.
+ */
+ private static ConcurrentMap<String, MessageFormat> messageMap = new ConcurrentHashMap<String, MessageFormat>();
+ private static final ResourceBundle RESOURCES = new CombinedResources("org.apache.commons.vfs2.Resources");
+
+ private Messages()
+ {
+ }
+
+ /**
+ * Formats a message.
+ *
+ * @param code The message code.
+ * @return The formatted message.
+ */
+ public static String getString(final String code)
+ {
+ return getString(code, new Object[0]);
+ }
+
+ /**
+ * Formats a message.
+ *
+ * @param code
+ * The message code.
+ * @param param
+ * The message parameter.
+ * @return The formatted message.
+ * @deprecated Will be removed in 3.0 in favor of {@link #getString(String, Object[])} When removed, calls to this
+ * method will automatically recompile to {@link #getString(String, Object[])}
+ */
+ @Deprecated
+ public static String getString(final String code, final Object param)
+ {
+ return getString(code, new Object[]{param});
+ }
+
+ /**
+ * Formats a message.
+ *
+ * @param code The message code.
+ * @param params The message parameters.
+ * @return The formatted message.
+ */
+ public static String getString(final String code, final Object... params)
+ {
+ try
+ {
+ if (code == null)
+ {
+ return null;
+ }
+
+ final MessageFormat msg = findMessage(code);
+ return msg.format(params);
+ }
+ catch (final MissingResourceException mre)
+ {
+ return "Unknown message with code \"" + code + "\".";
+ }
+ }
+
+ /**
+ * Locates a message by its code.
+ */
+ private static MessageFormat findMessage(final String code)
+ throws MissingResourceException
+ {
+ // Check if the message is cached
+ MessageFormat msg = messageMap.get(code);
+ if (msg != null)
+ {
+ return msg;
+ }
+
+ final String msgText = RESOURCES.getString(code);
+ msg = new MessageFormat(msgText);
+ messageMap.putIfAbsent(code, msg);
+ return messageMap.get(code);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/util/MonitorInputStream.java b/trunk/core/src/main/java/org/apache/commons/vfs2/util/MonitorInputStream.java
new file mode 100644
index 0000000..ce8f4e3
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/util/MonitorInputStream.java
@@ -0,0 +1,169 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.util;
+
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicLong;
+
+/**
+ * An InputStream that provides buffering and end-of-stream monitoring.
+ */
+public class MonitorInputStream
+ extends BufferedInputStream
+{
+ private final AtomicBoolean finished = new AtomicBoolean(false);
+ private final AtomicLong count = new AtomicLong(0);
+
+ public MonitorInputStream(final InputStream in)
+ {
+ super(in);
+ }
+
+
+ /**
+ * Returns 0 if the stream is at eof, else the underlaying inputStream will be queried.
+ * @return The number of bytes that are available.
+ * @throws IOException if an error occurs.
+ * @since 2.0
+ */
+ @Override
+ public synchronized int available() throws IOException
+ {
+ if (finished.get())
+ {
+ return 0;
+ }
+
+ return super.available();
+ }
+
+ /**
+ * Reads a character.
+ * @return The character that was read as an integer.
+ * @throws IOException if an error occurs.
+ */
+ @Override
+ public int read() throws IOException
+ {
+ if (finished.get())
+ {
+ return -1;
+ }
+
+ final int ch = super.read();
+ if (ch != -1)
+ {
+ count.incrementAndGet();
+ return ch;
+ }
+
+ // End-of-stream
+ close();
+ return -1;
+ }
+
+ /**
+ * Reads bytes from this input stream.
+ * @param buffer A byte array in which to place the characters read.
+ * @param offset The offset at which to start reading.
+ * @param length The maximum number of bytes to read.
+ * @return The number of bytes read.
+ * @throws IOException if an error occurs.
+ */
+ @Override
+ public int read(final byte[] buffer, final int offset, final int length)
+ throws IOException
+ {
+ if (finished.get())
+ {
+ return -1;
+ }
+
+ final int nread = super.read(buffer, offset, length);
+ if (nread != -1)
+ {
+ count.addAndGet(nread);
+ return nread;
+ }
+
+ // End-of-stream
+ close();
+ return -1;
+ }
+
+ /**
+ * Closes this input stream and releases any system resources
+ * associated with the stream.
+ * @throws IOException if an error occurs.
+ */
+ @Override
+ public void close() throws IOException
+ {
+ final boolean closed = finished.getAndSet(true);
+ if (closed)
+ {
+ return;
+ }
+
+ // Close the stream
+ IOException exc = null;
+ try
+ {
+ super.close();
+ }
+ catch (final IOException ioe)
+ {
+ exc = ioe;
+ }
+
+ // Notify that the stream has been closed
+ try
+ {
+ onClose();
+ }
+ catch (final IOException ioe)
+ {
+ exc = ioe;
+ }
+
+ if (exc != null)
+ {
+ throw exc;
+ }
+ }
+
+ /**
+ * Called after the stream has been closed. This implementation does
+ * nothing.
+ * @throws IOException if an error occurs.
+ */
+ protected void onClose() throws IOException
+ {
+ }
+
+ /**
+ * Get the nuber of bytes read by this input stream.
+ * @return The number of bytes read by this input stream.
+ */
+ public long getCount()
+ {
+ return count.get();
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/util/MonitorOutputStream.java b/trunk/core/src/main/java/org/apache/commons/vfs2/util/MonitorOutputStream.java
new file mode 100644
index 0000000..fa86905
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/util/MonitorOutputStream.java
@@ -0,0 +1,177 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.util;
+
+import java.io.BufferedOutputStream;
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.concurrent.atomic.AtomicBoolean;
+
+import org.apache.commons.vfs2.FileSystemException;
+
+/**
+ * An OutputStream that provides buffering and end-of-stream monitoring.
+ */
+public class MonitorOutputStream
+ extends BufferedOutputStream
+{
+ private final AtomicBoolean finished = new AtomicBoolean(false);
+
+ public MonitorOutputStream(final OutputStream out)
+ {
+ super(out);
+ }
+
+ /**
+ * Closes this output stream.
+ * <p>
+ * This makes sure the buffers are flushed, close the output
+ * stream and it will call {@link #onClose()}
+ * and re-throw last exception from any of the three.
+ * <p>
+ * This does nothing if the stream is closed already.
+ *
+ * @throws IOException if an error occurs.
+ */
+ @Override
+ public void close() throws IOException
+ {
+ // do not use super.close()
+ // on Java 8 it might throw self suppression, see JDK-8042377
+ // in older Java it silently ignores flush() errors
+ if (finished.getAndSet(true))
+ {
+ return;
+ }
+
+ IOException exc = null;
+
+ // flush the buffer and out stream
+ try
+ {
+ super.flush();
+ }
+ catch (final IOException ioe)
+ {
+ exc = ioe;
+ }
+
+ // close the out stream without using super.close()
+ try
+ {
+ super.out.close();
+ }
+ catch (final IOException ioe)
+ {
+ exc = ioe;
+ }
+
+ // Notify of end of output
+ try
+ {
+ onClose();
+ }
+ catch (final IOException ioe)
+ {
+ exc = ioe;
+ }
+
+ if (exc != null)
+ {
+ throw exc;
+ }
+ }
+
+
+ /**
+ * @param b The character to write.
+ * @throws IOException if an error occurs.
+ * @since 2.0
+ */
+ @Override
+ public synchronized void write(final int b) throws IOException
+ {
+ assertOpen();
+ super.write(b);
+ }
+
+ /**
+ * @param b The byte array.
+ * @param off The offset into the array.
+ * @param len The number of bytes to write.
+ * @throws IOException if an error occurs.
+ * @since 2.0
+ */
+ @Override
+ public synchronized void write(final byte[] b, final int off, final int len) throws IOException
+ {
+ assertOpen();
+ super.write(b, off, len);
+ }
+
+ /**
+ * @throws IOException if an error occurs.
+ * @since 2.0
+ */
+ @Override
+ public synchronized void flush() throws IOException
+ {
+ assertOpen();
+ super.flush();
+ }
+
+ /**
+ * @param b The byte array.
+ * @throws IOException if an error occurs.
+ * @since 2.0
+ */
+ @Override
+ public void write(final byte[] b) throws IOException
+ {
+ assertOpen();
+ super.write(b);
+ }
+
+ /**
+ * Check if file is still open.
+ * <p>
+ * This is a workaround for an oddity with Java's BufferedOutputStream where you can write to
+ * even if the stream has been closed.
+ *
+ * @throws FileSystemException if already closed.
+ * @since 2.0
+ */
+ protected void assertOpen() throws FileSystemException
+ {
+ if (finished.get())
+ {
+ throw new FileSystemException("vfs.provider/closed.error");
+ }
+ }
+
+ /**
+ * Called after this stream is closed.
+ * <p>
+ * This implementation does nothing.
+ *
+ * @throws IOException if an error occurs.
+ */
+ // IOException is needed because subclasses may need to throw it
+ protected void onClose() throws IOException
+ {
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/util/MonitorRandomAccessContent.java b/trunk/core/src/main/java/org/apache/commons/vfs2/util/MonitorRandomAccessContent.java
new file mode 100644
index 0000000..486a23e
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/util/MonitorRandomAccessContent.java
@@ -0,0 +1,293 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.util;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+import org.apache.commons.vfs2.RandomAccessContent;
+
+/**
+ * A RandomAccessContent that provides end-of-stream monitoring.
+ */
+public class MonitorRandomAccessContent implements RandomAccessContent
+{
+ private final RandomAccessContent content;
+ private boolean finished;
+
+ public MonitorRandomAccessContent(final RandomAccessContent content)
+ {
+ this.content = content;
+ }
+
+ /**
+ * Called after this stream is closed.
+ *
+ * @throws IOException if subclass throws it.
+ */
+ @SuppressWarnings("unused") // IOException is needed because subclasses may need to throw it
+ protected void onClose() throws IOException
+ {
+ }
+
+ /**
+ * Closes this content.
+ * @throws IOException if an error occurs.
+ */
+ @Override
+ public void close() throws IOException
+ {
+ if (finished)
+ {
+ return;
+ }
+
+ // Close the output stream
+ IOException exc = null;
+ try
+ {
+ content.close();
+ }
+ catch (final IOException ioe)
+ {
+ exc = ioe;
+ }
+
+ // Notify of end of output
+ exc = null;
+ try
+ {
+ onClose();
+ }
+ catch (final IOException ioe)
+ {
+ exc = ioe;
+ }
+
+ finished = true;
+
+ if (exc != null)
+ {
+ throw exc;
+ }
+ }
+
+ @Override
+ public long getFilePointer() throws IOException
+ {
+ return content.getFilePointer();
+ }
+
+ @Override
+ public void seek(final long pos) throws IOException
+ {
+ content.seek(pos);
+ }
+
+ @Override
+ public long length() throws IOException
+ {
+ return content.length();
+ }
+
+ @Override
+ public void write(final int b) throws IOException
+ {
+ content.write(b);
+ }
+
+ @Override
+ public void write(final byte[] b) throws IOException
+ {
+ content.write(b);
+ }
+
+ @Override
+ public void write(final byte[] b, final int off, final int len) throws IOException
+ {
+ content.write(b, off, len);
+ }
+
+ @Override
+ public void writeBoolean(final boolean v) throws IOException
+ {
+ content.writeBoolean(v);
+ }
+
+ @Override
+ public void writeByte(final int v) throws IOException
+ {
+ content.writeByte(v);
+ }
+
+ @Override
+ public void writeShort(final int v) throws IOException
+ {
+ content.writeShort(v);
+ }
+
+ @Override
+ public void writeChar(final int v) throws IOException
+ {
+ content.writeChar(v);
+ }
+
+ @Override
+ public void writeInt(final int v) throws IOException
+ {
+ content.writeInt(v);
+ }
+
+ @Override
+ public void writeLong(final long v) throws IOException
+ {
+ content.writeLong(v);
+ }
+
+ @Override
+ public void writeFloat(final float v) throws IOException
+ {
+ content.writeFloat(v);
+ }
+
+ @Override
+ public void writeDouble(final double v) throws IOException
+ {
+ content.writeDouble(v);
+ }
+
+ @Override
+ public void writeBytes(final String s) throws IOException
+ {
+ content.writeBytes(s);
+ }
+
+ @Override
+ public void writeChars(final String s) throws IOException
+ {
+ content.writeChars(s);
+ }
+
+ @Override
+ public void writeUTF(final String str) throws IOException
+ {
+ content.writeUTF(str);
+ }
+
+ @Override
+ public void readFully(final byte[] b) throws IOException
+ {
+ content.readFully(b);
+ }
+
+ @Override
+ public void readFully(final byte[] b, final int off, final int len) throws IOException
+ {
+ content.readFully(b, off, len);
+ }
+
+ @Override
+ public int skipBytes(final int n) throws IOException
+ {
+ return content.skipBytes(n);
+ }
+
+ @Override
+ public void setLength(final long newLength) throws IOException
+ {
+ content.setLength(newLength);
+ }
+
+ @Override
+ public boolean readBoolean() throws IOException
+ {
+ return content.readBoolean();
+ }
+
+ @Override
+ public byte readByte() throws IOException
+ {
+ return content.readByte();
+ }
+
+ @Override
+ public int readUnsignedByte() throws IOException
+ {
+ return content.readUnsignedByte();
+ }
+
+ @Override
+ public short readShort() throws IOException
+ {
+ return content.readShort();
+ }
+
+ @Override
+ public int readUnsignedShort() throws IOException
+ {
+ return content.readUnsignedShort();
+ }
+
+ @Override
+ public char readChar() throws IOException
+ {
+ return content.readChar();
+ }
+
+ @Override
+ public int readInt() throws IOException
+ {
+ return content.readInt();
+ }
+
+ @Override
+ public long readLong() throws IOException
+ {
+ return content.readLong();
+ }
+
+ @Override
+ public float readFloat() throws IOException
+ {
+ return content.readFloat();
+ }
+
+ @Override
+ public double readDouble() throws IOException
+ {
+ return content.readDouble();
+ }
+
+ @Override
+ public String readLine() throws IOException
+ {
+ return content.readLine();
+ }
+
+ @Override
+ public String readUTF() throws IOException
+ {
+ return content.readUTF();
+ }
+
+ @Override
+ public InputStream getInputStream() throws IOException
+ {
+ return content.getInputStream();
+ }
+
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/util/Os.java b/trunk/core/src/main/java/org/apache/commons/vfs2/util/Os.java
new file mode 100644
index 0000000..f9a9ced
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/util/Os.java
@@ -0,0 +1,352 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.util;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+
+/**
+ * Class to help determining the OS.
+ */
+public final class Os
+{
+ /**
+ * All Windows based OSes.
+ */
+ public static final OsFamily OS_FAMILY_WINDOWS = new OsFamily("windows");
+
+ /**
+ * All DOS based OSes.
+ */
+ public static final OsFamily OS_FAMILY_DOS = new OsFamily("dos");
+
+ /**
+ * All Windows NT based OSes.
+ */
+ public static final OsFamily OS_FAMILY_WINNT =
+ new OsFamily("nt", new OsFamily[]{OS_FAMILY_WINDOWS});
+
+ /**
+ * All Windows 9x based OSes.
+ */
+ public static final OsFamily OS_FAMILY_WIN9X =
+ new OsFamily("win9x", new OsFamily[]{OS_FAMILY_WINDOWS, OS_FAMILY_DOS});
+
+ /**
+ * OS/2.
+ */
+ public static final OsFamily OS_FAMILY_OS2 =
+ new OsFamily("os/2", new OsFamily[]{OS_FAMILY_DOS});
+
+ /**
+ * Netware.
+ */
+ public static final OsFamily OS_FAMILY_NETWARE =
+ new OsFamily("netware");
+
+ /**
+ * All UNIX based OSes.
+ */
+ public static final OsFamily OS_FAMILY_UNIX = new OsFamily("unix");
+
+ /**
+ * All Mac based OSes.
+ */
+ public static final OsFamily OS_FAMILY_MAC = new OsFamily("mac");
+
+ /**
+ * OSX.
+ */
+ public static final OsFamily OS_FAMILY_OSX =
+ new OsFamily("osx", new OsFamily[]{OS_FAMILY_UNIX, OS_FAMILY_MAC});
+
+ private static final String OS_NAME =
+ System.getProperty("os.name").toLowerCase(Locale.US);
+ private static final String OS_ARCH =
+ System.getProperty("os.arch").toLowerCase(Locale.US);
+ private static final String OS_VERSION =
+ System.getProperty("os.version").toLowerCase(Locale.US);
+ private static final String PATH_SEP = File.pathSeparator;
+ private static final OsFamily OS_FAMILY;
+ private static final OsFamily[] OS_ALL_FAMILIES;
+
+ private static final OsFamily[] ALL_FAMILIES = new OsFamily[]
+ {
+ OS_FAMILY_DOS,
+ OS_FAMILY_MAC,
+ OS_FAMILY_NETWARE,
+ OS_FAMILY_OS2,
+ OS_FAMILY_OSX,
+ OS_FAMILY_UNIX,
+ OS_FAMILY_WINDOWS,
+ OS_FAMILY_WINNT,
+ OS_FAMILY_WIN9X
+ };
+
+ static
+ {
+ OS_FAMILY = determineOsFamily();
+ OS_ALL_FAMILIES = determineAllFamilies();
+ }
+
+ /**
+ * Private constructor to block instantiation.
+ */
+ private Os()
+ {
+ }
+
+ /**
+ * Determines if the OS on which Ant is executing matches the given OS
+ * version.
+ * @param version The version to check.
+ * @return true if the version matches.
+ */
+ public static boolean isVersion(final String version)
+ {
+ return isOs((OsFamily) null, null, null, version);
+ }
+
+ /**
+ * Determines if the OS on which Ant is executing matches the given OS
+ * architecture.
+ * @param arch The architecture to check.
+ * @return true if the architecture mataches.
+ */
+ public static boolean isArch(final String arch)
+ {
+ return isOs((OsFamily) null, null, arch, null);
+ }
+
+ /**
+ * Determines if the OS on which Ant is executing matches the given OS
+ * family.
+ * @param family The family to check.
+ * @return true if the family matches.
+ */
+ public static boolean isFamily(final String family)
+ {
+ return isOs(family, null, null, null);
+ }
+
+ /**
+ * Determines if the OS on which Ant is executing matches the given OS
+ * family.
+ * @param family The family to check.
+ * @return true if the family matches.
+ */
+ public static boolean isFamily(final OsFamily family)
+ {
+ return isOs(family, null, null, null);
+ }
+
+ /**
+ * Determines if the OS on which Ant is executing matches the given OS name.
+ *
+ * @param name Description of Parameter
+ * @return The Name value
+ * @since 1.7
+ */
+ public static boolean isName(final String name)
+ {
+ return isOs((OsFamily) null, name, null, null);
+ }
+
+ /**
+ * Determines if the OS on which Ant is executing matches the given OS
+ * family, name, architecture and version.
+ *
+ * @param family The OS family
+ * @param name The OS name
+ * @param arch The OS architecture
+ * @param version The OS version
+ * @return The Os value
+ */
+ public static boolean isOs(final String family,
+ final String name,
+ final String arch,
+ final String version)
+ {
+ return isOs(getFamily(family), name, arch, version);
+ }
+
+ /**
+ * Determines if the OS on which Ant is executing matches the given OS
+ * family, name, architecture and version.
+ *
+ * @param family The OS family
+ * @param name The OS name
+ * @param arch The OS architecture
+ * @param version The OS version
+ * @return The Os value
+ */
+ public static boolean isOs(final OsFamily family,
+ final String name,
+ final String arch,
+ final String version)
+ {
+ if (family != null || name != null || arch != null || version != null)
+ {
+ final boolean isFamily = familyMatches(family);
+ final boolean isName = nameMatches(name);
+ final boolean isArch = archMatches(arch);
+ final boolean isVersion = versionMatches(version);
+
+ return isFamily && isName && isArch && isVersion;
+ }
+ else
+ {
+ return false;
+ }
+ }
+
+ /**
+ * Locates an OsFamily by name (case-insensitive).
+ *
+ * @param name The family name to lookup.
+ * @return the OS family, or null if not found.
+ */
+ public static OsFamily getFamily(final String name)
+ {
+ for (final OsFamily osFamily : ALL_FAMILIES)
+ {
+ if (osFamily.getName().equalsIgnoreCase(name))
+ {
+ return osFamily;
+ }
+ }
+
+ return null;
+ }
+
+ private static boolean versionMatches(final String version)
+ {
+ boolean isVersion = true;
+ if (version != null)
+ {
+ isVersion = version.equalsIgnoreCase(OS_VERSION);
+ }
+ return isVersion;
+ }
+
+ private static boolean archMatches(final String arch)
+ {
+ boolean isArch = true;
+ if (arch != null)
+ {
+ isArch = arch.equalsIgnoreCase(OS_ARCH);
+ }
+ return isArch;
+ }
+
+ private static boolean nameMatches(final String name)
+ {
+ boolean isName = true;
+ if (name != null)
+ {
+ isName = name.equalsIgnoreCase(OS_NAME);
+ }
+ return isName;
+ }
+
+ private static boolean familyMatches(final OsFamily family)
+ {
+ if (family == null)
+ {
+ return false;
+ }
+ for (final OsFamily osFamily : OS_ALL_FAMILIES)
+ {
+ if (family == osFamily)
+ {
+ return true;
+ }
+ }
+ return false;
+ }
+
+ private static OsFamily[] determineAllFamilies()
+ {
+ // Determine all families the current OS belongs to
+ final Set<OsFamily> allFamilies = new HashSet<OsFamily>();
+ if (OS_FAMILY != null)
+ {
+ final List<OsFamily> queue = new ArrayList<OsFamily>();
+ queue.add(OS_FAMILY);
+ while (queue.size() > 0)
+ {
+ final OsFamily family = queue.remove(0);
+ allFamilies.add(family);
+ final OsFamily[] families = family.getFamilies();
+ for (final OsFamily parent : families)
+ {
+ queue.add(parent);
+ }
+ }
+ }
+ return allFamilies.toArray(new OsFamily[allFamilies.size()]);
+ }
+
+ private static OsFamily determineOsFamily()
+ {
+ // Determine the most specific OS family
+ if (OS_NAME.indexOf("windows") > -1)
+ {
+ if (OS_NAME.indexOf("xp") > -1
+ || OS_NAME.indexOf("2000") > -1
+ || OS_NAME.indexOf("nt") > -1)
+ {
+ return OS_FAMILY_WINNT;
+ }
+ else
+ {
+ return OS_FAMILY_WIN9X;
+ }
+ }
+ else if (OS_NAME.indexOf("os/2") > -1)
+ {
+ return OS_FAMILY_OS2;
+ }
+ else if (OS_NAME.indexOf("netware") > -1)
+ {
+ return OS_FAMILY_NETWARE;
+ }
+ else if (OS_NAME.indexOf("mac") > -1)
+ {
+ if (OS_NAME.endsWith("x"))
+ {
+ return OS_FAMILY_OSX;
+ }
+ else
+ {
+ return OS_FAMILY_MAC;
+ }
+ }
+ else if (PATH_SEP.equals(":"))
+ {
+ return OS_FAMILY_UNIX;
+ }
+ else
+ {
+ return null;
+ }
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/util/OsFamily.java b/trunk/core/src/main/java/org/apache/commons/vfs2/util/OsFamily.java
new file mode 100644
index 0000000..7382f69
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/util/OsFamily.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.util;
+
+/**
+ * An enumerated type, which represents an OS family.
+ */
+public final class OsFamily
+{
+ private final String name;
+ private final OsFamily[] families;
+
+ OsFamily(final String name)
+ {
+ this.name = name;
+ families = new OsFamily[0];
+ }
+
+ OsFamily(final String name, final OsFamily[] families)
+ {
+ this.name = name;
+ this.families = families;
+ }
+
+ /**
+ * Returns the name of this family.
+ * @return The name of this family.
+ */
+ public String getName()
+ {
+ return name;
+ }
+
+ /**
+ * Returns the OS families that this family belongs to.
+ * @return an array of OSFamily objects that this family belongs to.
+ */
+ public OsFamily[] getFamilies()
+ {
+ return families;
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/util/PosixPermissions.java b/trunk/core/src/main/java/org/apache/commons/vfs2/util/PosixPermissions.java
new file mode 100644
index 0000000..62e800c
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/util/PosixPermissions.java
@@ -0,0 +1,296 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.commons.vfs2.util;
+
+import java.util.EnumMap;
+import java.util.Map;
+
+/**
+ * UNIX permissions.
+ *
+ * @since 2.1
+ */
+public class PosixPermissions
+{
+
+ /**
+ * Permission types.
+ */
+ public static enum Type
+ {
+ /**
+ * User right readable.
+ */
+ UserReadable(00400),
+
+ /**
+ * User right writable.
+ */
+ UserWritable(00200),
+
+ /**
+ * User right executable.
+ */
+ UserExecutable(00100),
+
+ /**
+ * Group right readable.
+ */
+ GroupReadable(00040),
+
+ /**
+ * Group right writable.
+ */
+ GroupWritable(00020),
+
+ /**
+ * Group right executable.
+ */
+ GroupExecutable(00010),
+
+ /**
+ * Other right readable.
+ */
+ OtherReadable(00004),
+
+ /**
+ * Other right writable.
+ */
+ OtherWritable(00002),
+
+ /**
+ * Other right executable.
+ */
+ OtherExecutable(00001);
+
+ private final int mask;
+
+ /**
+ * Initialize with the mask
+ */
+ private Type(final int mask)
+ {
+ this.mask = mask;
+ }
+
+ /**
+ * Return the mask for this permission.
+ *
+ * @return the mask for this permission.
+ */
+ public int getMask()
+ {
+ return this.mask;
+ }
+
+ }
+
+ /**
+ * Current permissions.
+ */
+ private final int permissions;
+
+ /**
+ * If the user is the owner of the file.
+ */
+ private final boolean isOwner;
+
+ /**
+ * If one user group is the group of the file.
+ */
+ private final boolean isInGroup;
+
+ /**
+ * Creates a new PosixPermissions object.
+ *
+ * @param permissions
+ * The permissions
+ * @param isOwner
+ * true if the user is the owner of the file
+ * @param isInGroup
+ * true if the user is a group owner of the file
+ */
+ public PosixPermissions(final int permissions, final boolean isOwner, final boolean isInGroup)
+ {
+ this.permissions = permissions;
+ this.isOwner = isOwner;
+ this.isInGroup = isInGroup;
+ }
+
+ /**
+ * Computes new permission from old ones.
+ *
+ * @param values
+ * The permissions to set.
+ * @return The new permissions.
+ */
+ private int computeNewPermissions(final Map<Type, Boolean> values)
+ {
+ int newPerms = this.permissions;
+ for (final Map.Entry<Type, Boolean> entry : values.entrySet())
+ {
+ final Type type = entry.getKey();
+ if (entry.getValue())
+ {
+ newPerms |= type.getMask();
+ }
+ else
+ {
+ newPerms &= ~type.getMask();
+ }
+ }
+ return newPerms;
+ }
+
+ /**
+ * Tests whether the bit corresponding to the permission is set.
+ *
+ * @return whether the bit corresponding to the permission is set.
+ */
+ private boolean get(final Type type)
+ {
+ return (type.getMask() & this.permissions) != 0;
+ }
+
+ /**
+ * Gets permissions.
+ *
+ * @return permissions.
+ */
+ public int getPermissions()
+ {
+ return this.permissions;
+ }
+
+ /**
+ * Gets whether the permissions are executable.
+ *
+ * @return whether the permissions are executable.
+ */
+ public boolean isExecutable()
+ {
+ if (this.isOwner)
+ {
+ return this.get(Type.UserExecutable);
+ }
+ if (this.isInGroup)
+ {
+ return this.get(Type.GroupExecutable);
+ }
+ return this.get(Type.OtherExecutable);
+ }
+
+ /**
+ * Gets whether the permissions are readable.
+ *
+ * @return whether the permissions are readable.
+ */
+ public boolean isReadable()
+ {
+ if (this.isOwner)
+ {
+ return this.get(Type.UserReadable);
+ }
+ if (this.isInGroup)
+ {
+ return this.get(Type.GroupReadable);
+ }
+ return this.get(Type.OtherReadable);
+ }
+
+ /**
+ * Gets whether the permissions are writable.
+ *
+ * @return whether the permissions are writable.
+ */
+ public boolean isWritable()
+ {
+ if (this.isOwner)
+ {
+ return this.get(Type.UserWritable);
+ }
+ if (this.isInGroup)
+ {
+ return this.get(Type.GroupWritable);
+ }
+ return this.get(Type.OtherWritable);
+ }
+
+ /**
+ * Creates new permissions based on these permissions.
+ *
+ * @param executable
+ * Whether the new permissions should be readable.
+ * @param ownerOnly
+ * Whether the new permissions are only for the owner.
+ * @return the new permissions.
+ */
+ public int makeExecutable(final boolean executable, final boolean ownerOnly)
+ {
+ final EnumMap<Type, Boolean> map = new EnumMap<Type, Boolean>(Type.class);
+ map.put(Type.UserExecutable, executable);
+ if (!ownerOnly)
+ {
+ map.put(Type.GroupExecutable, executable);
+ map.put(Type.OtherExecutable, executable);
+ }
+ return this.computeNewPermissions(map);
+ }
+
+ /**
+ * Creates new permissions based on these permissions.
+ *
+ * @param readable
+ * Whether the new permissions should be readable.
+ * @param ownerOnly
+ * Whether the new permissions are only for the owner.
+ * @return the new permissions.
+ */
+ public Integer makeReadable(final boolean readable, final boolean ownerOnly)
+ {
+ final EnumMap<Type, Boolean> map = new EnumMap<Type, Boolean>(Type.class);
+ map.put(Type.UserReadable, readable);
+ if (!ownerOnly)
+ {
+ map.put(Type.GroupReadable, readable);
+ map.put(Type.OtherReadable, readable);
+ }
+ return this.computeNewPermissions(map);
+ }
+
+ /**
+ * Creates new permissions based on these permissions.
+ *
+ * @param writable
+ * Whether the new permissions should be readable.
+ * @param ownerOnly
+ * Whether the new permissions are only for the owner.
+ * @return the new permissions.
+ */
+ public Integer makeWritable(final boolean writable, final boolean ownerOnly)
+ {
+ final EnumMap<Type, Boolean> map = new EnumMap<Type, Boolean>(Type.class);
+ map.put(Type.UserWritable, writable);
+ if (!ownerOnly)
+ {
+ map.put(Type.GroupWritable, writable);
+ map.put(Type.OtherWritable, writable);
+ }
+ return this.computeNewPermissions(map);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/util/RandomAccessMode.java b/trunk/core/src/main/java/org/apache/commons/vfs2/util/RandomAccessMode.java
new file mode 100644
index 0000000..67a9870
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/util/RandomAccessMode.java
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.util;
+
+/**
+ * An enumerated type representing the modes of a random access content.
+ */
+public enum RandomAccessMode
+{
+ /**
+ * read.
+ */
+ READ(true, false),
+
+ /**
+ * read/write.
+ */
+ READWRITE(true, true);
+
+
+ private final boolean read;
+ private final boolean write;
+
+ private RandomAccessMode(final boolean read, final boolean write)
+ {
+ this.read = read;
+ this.write = write;
+ }
+
+ public boolean requestRead()
+ {
+ return read;
+ }
+
+ public boolean requestWrite()
+ {
+ return write;
+ }
+
+ /**
+ * @return The mode String.
+ * @since 2.0
+ * */
+ public String getModeString()
+ {
+ if (requestRead())
+ {
+ if (requestWrite())
+ {
+ return "rw"; // NON-NLS
+ }
+ else
+ {
+ return "r"; // NON-NLS
+ }
+ }
+ else if (requestWrite())
+ {
+ return "w"; // NON-NLS
+ }
+
+ return "";
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/util/UserAuthenticatorUtils.java b/trunk/core/src/main/java/org/apache/commons/vfs2/util/UserAuthenticatorUtils.java
new file mode 100644
index 0000000..74bc428
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/util/UserAuthenticatorUtils.java
@@ -0,0 +1,136 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.util;
+
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.UserAuthenticationData;
+import org.apache.commons.vfs2.UserAuthenticator;
+import org.apache.commons.vfs2.impl.DefaultFileSystemConfigBuilder;
+
+/**
+ * Helps with authentication.
+ */
+public final class UserAuthenticatorUtils
+{
+ private UserAuthenticatorUtils()
+ {
+ }
+
+ /**
+ * Gets data of given type from the UserAuthenticationData or null if there is no data or data
+ * of this type available.
+ *
+ * @param data The UserAuthenticationData.
+ * @param type The type of the element to retrieve.
+ * @param overriddenValue The default value.
+ * @return The data of the given type as a character array or null if the data is not available.
+ */
+ public static char[] getData(final UserAuthenticationData data, final UserAuthenticationData.Type type,
+ final char[] overriddenValue)
+ {
+ if (overriddenValue != null)
+ {
+ return overriddenValue;
+ }
+
+ if (data == null)
+ {
+ return null;
+ }
+
+ return data.getData(type);
+ }
+
+ /**
+ * Authenticates if there is an authenticator, else returns null.
+ *
+ * @param opts The FileSystemOptions.
+ * @param authenticatorTypes An array of types describing the data to be retrieved.
+ * @return A UserAuthenticationData object containing the data requested.
+ */
+ public static UserAuthenticationData authenticate(final FileSystemOptions opts,
+ final UserAuthenticationData.Type[] authenticatorTypes)
+ {
+ final UserAuthenticator auth = DefaultFileSystemConfigBuilder.getInstance().getUserAuthenticator(opts);
+ return authenticate(auth, authenticatorTypes);
+ }
+
+ /**
+ * Authenticates if there is an authenticator, else returns null.
+ *
+ * @param auth The UserAuthenticator.
+ * @param authenticatorTypes An array of types describing the data to be retrieved.
+ * @return A UserAuthenticationData object containing the data requested.
+ */
+ public static UserAuthenticationData authenticate(final UserAuthenticator auth,
+ final UserAuthenticationData.Type[] authenticatorTypes)
+ {
+ if (auth == null)
+ {
+ return null;
+ }
+
+ return auth.requestAuthentication(authenticatorTypes);
+ }
+
+ /**
+ * Converts a string to a char array (null-safe).
+ *
+ * @param string The String to convert.
+ * @return The character array.
+ */
+ public static char[] toChar(final String string)
+ {
+ if (string == null)
+ {
+ return null;
+ }
+
+ return string.toCharArray();
+ }
+
+ /**
+ * Cleans up the data in the UerAuthenticationData (null-safe).
+ *
+ * @param authData The UserAuthenticationDAta.
+ */
+ public static void cleanup(final UserAuthenticationData authData)
+ {
+ if (authData == null)
+ {
+ return;
+ }
+
+ authData.cleanup();
+ }
+
+ /**
+ * Converts the given data to a string (null-safe).
+ *
+ * @param data A character array containing the data to convert to a String.
+ * @return The String.
+ */
+ public static String toString(final char[] data)
+ {
+ if (data == null)
+ {
+ return null;
+ }
+
+ return new String(data);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/util/WeakRefFileListener.java b/trunk/core/src/main/java/org/apache/commons/vfs2/util/WeakRefFileListener.java
new file mode 100644
index 0000000..73aa6b5
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/util/WeakRefFileListener.java
@@ -0,0 +1,124 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.util;
+
+import java.lang.ref.WeakReference;
+
+import org.apache.commons.vfs2.FileChangeEvent;
+import org.apache.commons.vfs2.FileListener;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+
+/**
+ * Wrap a listener with a WeakReference.
+ *
+ * @since 2.0
+ */
+public class WeakRefFileListener implements FileListener
+{
+ private final FileSystem fs;
+ private final FileName name;
+ private final WeakReference<FileListener> listener;
+
+ protected WeakRefFileListener(final FileObject file, final FileListener listener)
+ {
+ this.fs = file.getFileSystem();
+ this.name = file.getName();
+ this.listener = new WeakReference<FileListener>(listener);
+ }
+
+ /**
+ * This will install the {@code listener} at the given {@code file}.
+ * @param file The FileObject to listen on.
+ * @param listener The FileListener
+ */
+ public static void installListener(final FileObject file, final FileListener listener)
+ {
+ final WeakRefFileListener weakListener = new WeakRefFileListener(file, listener);
+
+ file.getFileSystem().addListener(file, new WeakRefFileListener(file, weakListener));
+ }
+
+ /**
+ * returns the wrapped listener. If it is gone, the WeakRefFileListener wrapper will
+ * remove itself from the list of listeners.
+ * @return The FileListener.
+ * @throws Exception if an error occurs.
+ */
+ protected FileListener getListener() throws Exception
+ {
+ final FileListener listener = this.listener.get();
+ if (listener == null)
+ {
+ final FileObject file = fs.resolveFile(name);
+ file.getFileSystem().removeListener(file, this);
+ }
+ return listener;
+ }
+
+ /**
+ * Called when a file is created.
+ * @param event The FileChangeEvent.
+ * @throws Exception if an error occurs.
+ */
+ @Override
+ public void fileCreated(final FileChangeEvent event) throws Exception
+ {
+ final FileListener listener = getListener();
+ if (listener == null)
+ {
+ return;
+ }
+ listener.fileCreated(event);
+ }
+
+ /**
+ * Called when a file is deleted.
+ * @param event The FileChangeEvent.
+ * @throws Exception if an error occurs.
+ */
+ @Override
+ public void fileDeleted(final FileChangeEvent event) throws Exception
+ {
+ final FileListener listener = getListener();
+ if (listener == null)
+ {
+ return;
+ }
+ listener.fileDeleted(event);
+ }
+
+ /**
+ * Called when a file is changed.
+ * <p>
+ * This will only happen if you monitor the file using {@link org.apache.commons.vfs2.FileMonitor}.
+ *
+ * @param event The FileChangeEvent.
+ * @throws Exception if an error occurs.
+ */
+ @Override
+ public void fileChanged(final FileChangeEvent event) throws Exception
+ {
+ final FileListener listener = getListener();
+ if (listener == null)
+ {
+ return;
+ }
+ listener.fileChanged(event);
+ }
+}
diff --git a/trunk/core/src/main/java/org/apache/commons/vfs2/util/package.html b/trunk/core/src/main/java/org/apache/commons/vfs2/util/package.html
new file mode 100644
index 0000000..c9af968
--- /dev/null
+++ b/trunk/core/src/main/java/org/apache/commons/vfs2/util/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>Utility classes used by the VFS.</p>
+</body>
diff --git a/trunk/core/src/main/utils/create_archives.sh b/trunk/core/src/main/utils/create_archives.sh
new file mode 100755
index 0000000..83a1a3b
--- /dev/null
+++ b/trunk/core/src/main/utils/create_archives.sh
@@ -0,0 +1,106 @@
+#!/bin/sh
+
+## Licensed to the Apache Software Foundation (ASF) under one or more
+## contributor license agreements. See the NOTICE file distributed with
+## this work for additional information regarding copyright ownership.
+## The ASF licenses this file to You under the Apache License, Version 2.0
+## (the "License"); you may not use this file except in compliance with
+## the License. You may obtain a copy of the License at
+##
+## http://www.apache.org/licenses/LICENSE-2.0
+##
+## Unless required by applicable law or agreed to in writing, software
+## distributed under the License is distributed on an "AS IS" BASIS,
+## WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+## See the License for the specific language governing permissions and
+## limitations under the License.
+
+set -e
+
+PRG="$0"
+
+while [ -h "$PRG" ]; do
+ ls=`ls -ld "$PRG"`
+ link=`expr "$ls" : '.*-> \(.*\)$'`
+ if expr "$link" : '.*/.*' > /dev/null; then
+ PRG="$link"
+ else
+ PRG=`dirname "$PRG"`/"$link"
+ fi
+done
+
+# Get standard environment variables
+PRGDIR=`dirname "$PRG"`
+
+cd $PRGDIR/../../..
+
+if [ ! -d target/test-classes/test-data/read-tests ]
+then
+ echo "Please run maven to have the environment setup correctly"
+ exit 1
+fi
+
+if [ ! -x "`type -p jar`" ]
+then
+ echo "cant execute jar?"
+ exit 1
+fi
+if [ ! -x "`type -p tar`" ]
+then
+ echo "cant execute tar?"
+ exit 1
+fi
+if [ ! -x "`type -p zip`" ]
+then
+ echo "cant execute zip?"
+ exit 1
+fi
+if [ ! -x "`type -p bzip2`" ]
+then
+ echo "cant execute bzip2?"
+ exit 1
+fi
+
+cd target/test-classes/test-data
+mkdir read-tests/emptydir
+
+rm -f test.jar test.tar test.tbz2 test.tgz test.zip
+rm -f nested.jar nested.tar nested.tbz2 nested.tgz nested.zip
+
+echo "Creating test.jar ..."
+jar -cvfm test.jar test.mf read-tests code
+
+echo "Creating test.tar ..."
+tar cvf test.tar read-tests code
+
+echo "Creating test.tbz2 ..."
+tar cjvf test.tbz2 read-tests code
+
+echo "Creating test.tgz ..."
+tar czvf test.tgz read-tests code
+
+echo "Creating test.zip ..."
+zip -r test.zip read-tests code
+
+echo "Creating nested.jar ..."
+jar cvf nested.jar test.jar
+
+echo "Creating nested.tar ..."
+tar cvf nested.tar test.tar
+
+echo "Creating nested.tbz2 ..."
+tar cjvf nested.tbz2 test.tbz2
+
+echo "Creating nested.tgz ..."
+tar czvf nested.tgz test.tgz
+
+echo "Creating nested.zip ..."
+zip nested.zip test.zip
+
+for i in test.jar test.tar test.tbz2 test.tgz test.zip nested.jar nested.tar nested.tbz2 nested.tgz nested.zip
+do
+ cp $i ../../../src/test/resources/test-data/$i
+done
+
+echo Done.
+
diff --git a/trunk/core/src/site/site.xml b/trunk/core/src/site/site.xml
new file mode 100644
index 0000000..44451fa
--- /dev/null
+++ b/trunk/core/src/site/site.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<project name="Commons VFS">
+
+ <bannerRight>
+ <name>Commons VFS</name>
+ <src>../images/vfs-logo-white.png</src>
+ <href>../index.html</href>
+ </bannerRight>
+
+ <body>
+ <links>
+ <item name="Commons VFS Home" href="../index.html"/>
+ </links>
+
+ <!-- menus inherited -->
+
+ <menu ref="reports"/>
+ </body>
+</project>
diff --git a/trunk/core/src/site/xdoc/index.xml b/trunk/core/src/site/xdoc/index.xml
new file mode 100644
index 0000000..775963b
--- /dev/null
+++ b/trunk/core/src/site/xdoc/index.xml
@@ -0,0 +1,39 @@
+<?xml version="1.0"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<document>
+ <properties>
+ <title>Apache Commons VFS Core</title>
+ <author email="dev@commons.apache.org">Apache Commons Developers</author>
+ </properties>
+
+ <body>
+
+ <section name="About Apache Commons VFS Core">
+ <p>
+ This is the core module containing the Apache Commons VFS API,
+ implementation as well as various
+ <a href="../filesystems.html">file system providers</a>.
+ </p><p>
+ The documentation on how to use the API can be found in the
+ <a href="../api.html">parent module</a>.
+ </p>
+ </section>
+
+ </body>
+</document>
diff --git a/trunk/core/src/test/java/code/ClassToLoad.java b/trunk/core/src/test/java/code/ClassToLoad.java
new file mode 100644
index 0000000..44d657c
--- /dev/null
+++ b/trunk/core/src/test/java/code/ClassToLoad.java
@@ -0,0 +1,31 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package code;
+
+/**
+ * The test class for the VFS classloader.
+ */
+public class ClassToLoad
+{
+ private final String m_message = "**PRIVATE**";
+
+ @Override
+ public String toString()
+ {
+ return m_message;
+ }
+}
diff --git a/trunk/core/src/test/java/code/sealed/AnotherClass.java b/trunk/core/src/test/java/code/sealed/AnotherClass.java
new file mode 100644
index 0000000..ecf53dc
--- /dev/null
+++ b/trunk/core/src/test/java/code/sealed/AnotherClass.java
@@ -0,0 +1,24 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package code.sealed;
+
+/**
+ * A test class for the ClassLoader tests.
+ */
+public class AnotherClass
+{
+}
diff --git a/trunk/core/src/test/java/com/jcraft/jsch/TestIdentityRepositoryFactory.java b/trunk/core/src/test/java/com/jcraft/jsch/TestIdentityRepositoryFactory.java
new file mode 100644
index 0000000..772e3ed
--- /dev/null
+++ b/trunk/core/src/test/java/com/jcraft/jsch/TestIdentityRepositoryFactory.java
@@ -0,0 +1,36 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.jcraft.jsch;
+
+import org.apache.commons.vfs2.provider.sftp.IdentityRepositoryFactory;
+
+/**
+ * Simple JSch identity repository factory (that just returns the default factory).
+ *
+ * This class is packaged in {@code com.jcraft.jsch} because {@code com.jcraft.jsch.LocalIdentityRepository} is
+ * declared with default scope.
+ *
+ * @version $Id$
+ */
+public class TestIdentityRepositoryFactory implements IdentityRepositoryFactory
+{
+ @Override
+ public IdentityRepository create(final JSch jsch)
+ {
+ return new LocalIdentityRepository(jsch);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/AbstractVfsTestCase.java b/trunk/core/src/test/java/org/apache/commons/AbstractVfsTestCase.java
new file mode 100644
index 0000000..bb261b9
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/AbstractVfsTestCase.java
@@ -0,0 +1,280 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons;
+
+import java.io.File;
+import java.io.IOException;
+import java.lang.reflect.Method;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import junit.framework.TestCase;
+
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.util.Messages;
+
+/**
+ * A base class for VFS tests. Provides utility methods for locating
+ * test resources.
+ */
+public abstract class AbstractVfsTestCase
+ extends TestCase
+{
+ private static File baseDir;
+
+ /** URL pattern */
+ private static final Pattern URL_PATTERN = Pattern.compile("[a-z]+://.*");
+
+ /** Password pattern */
+ private static final Pattern PASSWORD_PATTERN = Pattern.compile(":(?:[^/]+)@");
+
+ /**
+ * Returns the name of the package containing a class.
+ *
+ * @return The . delimited package name, or an empty string if the class
+ * is in the default package.
+ */
+ public static String getPackageName(final Class<?> clazz)
+ {
+ final Package pkg = clazz.getPackage();
+ if (null != pkg)
+ {
+ return pkg.getName();
+ }
+
+ final String name = clazz.getName();
+ if (-1 == name.lastIndexOf("."))
+ {
+ return "";
+ }
+ else
+ {
+ return name.substring(0, name.lastIndexOf("."));
+ }
+ }
+
+ /**
+ * Locates a test resource, and asserts that the resource exists
+ *
+ * @param name path of the resource, relative to this test's base directory.
+ */
+ public static File getTestResource(final String name)
+ {
+ return getTestResource(name, true);
+ }
+
+ /**
+ * Locates a test resource.
+ *
+ * @param name path of the resource, relative to this test's base directory.
+ */
+ public static File getTestResource(final String name, final boolean mustExist)
+ {
+ File file = new File(getTestDirectoryFile(), name);
+ file = getCanonicalFile(file);
+ if (mustExist)
+ {
+ assertTrue("Test file \"" + file + "\" does not exist.", file.exists());
+ }
+ else
+ {
+ assertTrue("Test file \"" + file + "\" should not exist.", !file.exists());
+ }
+
+ return file;
+ }
+
+ /**
+ * Locates the base directory for this test.
+ */
+ public static File getTestDirectoryFile()
+ {
+ if (baseDir == null)
+ {
+ final String baseDirProp = getTestDirectory();
+ // the directory maybe expressed as URI in certain environments
+ if (baseDirProp.startsWith("file://")) {
+ try {
+ baseDir = getCanonicalFile(new File(new URI(baseDirProp)));
+ } catch (final URISyntaxException e) {
+ baseDir = getCanonicalFile(new File(baseDirProp));
+ }
+ } else {
+ baseDir = getCanonicalFile(new File(baseDirProp));
+ }
+ }
+ return baseDir;
+ }
+
+ /**
+ * Returns the test directory as a String.
+ * <p>
+ * {@link #getTestDirectoryFile()} should be preferred.
+ *
+ * @return the test directory as a String
+ */
+ public static String getTestDirectory()
+ {
+ return System.getProperty("test.basedir", "target/test-classes/test-data");
+ }
+
+ public static String getResourceTestDirectory()
+ {
+ return System.getProperty("test.basedir.res", "test-data");
+ }
+
+ /**
+ * Locates a test directory, creating it if it does not exist.
+ *
+ * @param name path of the directory, relative to this test's base directory.
+ */
+ public static File getTestDirectory(final String name)
+ {
+ File file = new File(getTestDirectoryFile(), name);
+ file = getCanonicalFile(file);
+ assertTrue("Test directory \"" + file + "\" does not exist or is not a directory.",
+ file.isDirectory() || file.mkdirs());
+ return file;
+ }
+
+ /**
+ * Makes a file canonical
+ */
+ public static File getCanonicalFile(final File file)
+ {
+ try
+ {
+ return file.getCanonicalFile();
+ }
+ catch (final IOException e)
+ {
+ return file.getAbsoluteFile();
+ }
+ }
+
+ /**
+ * Asserts that an exception chain contains the expected messages.
+ *
+ * @param messages The messages, in order. A null entry in this array
+ * indicates that the message should be ignored.
+ */
+ public static void assertSameMessage(final String[] messages, final Throwable throwable)
+ {
+ Throwable current = throwable;
+ for (final String message : messages)
+ {
+ assertNotNull(current);
+ if (message != null)
+ {
+ assertEquals(message, current.getMessage());
+ }
+
+ // Get the next exception in the chain
+ current = getCause(current);
+ }
+ }
+
+ /**
+ * Returns the cause of an exception.
+ */
+ public static Throwable getCause(final Throwable throwable)
+ {
+ try
+ {
+ final Method method = throwable.getClass().getMethod("getCause", (Class[]) null);
+ return (Throwable) method.invoke(throwable, (Object[]) null);
+ }
+ catch (final Exception e)
+ {
+ return null;
+ }
+ }
+
+ /**
+ * Asserts that an exception contains the expected message.
+ */
+ public static void assertSameMessage(final String code,
+ final Throwable throwable)
+ {
+ assertSameMessage(code, new Object[0], throwable);
+ }
+
+ /**
+ * Asserts that an exception contains the expected message.
+ */
+ public static void assertSameMessage(final String code,
+ final Object[] params,
+ final Throwable throwable)
+ {
+ Object[] parmArray = params;
+ if (throwable instanceof FileSystemException)
+ {
+ final FileSystemException fse = (FileSystemException) throwable;
+
+ // Compare message code and params
+ assertEquals(code, fse.getCode());
+ assertEquals(params.length, fse.getInfo().length);
+ parmArray = new Object[params.length];
+ for (int i = 0; i < params.length; i++)
+ {
+ String value = String.valueOf(params[i]);
+ // mask passwords (VFS-169)
+ final Matcher urlMatcher = URL_PATTERN.matcher(value);
+ if (urlMatcher.find())
+ {
+ final Matcher pwdMatcher = PASSWORD_PATTERN.matcher(value);
+ value = pwdMatcher.replaceFirst(":***@");
+ }
+ assertEquals(value, fse.getInfo()[i]);
+ parmArray[i] = value;
+ }
+ }
+
+ // Compare formatted message
+ final String message = Messages.getString(code, parmArray);
+ assertEquals(message, throwable.getMessage());
+ }
+
+ /**
+ * Asserts that an exception contains the expected message.
+ */
+ public static void assertSameMessage(final String code,
+ final Object param,
+ final Throwable throwable)
+ {
+ assertSameMessage(code, new Object[]{param}, throwable);
+ }
+
+ /**
+ * Compares 2 objects for equality, nulls are equal. Used by the test
+ * classes' equals() methods.
+ */
+ public static boolean equals(final Object o1, final Object o2)
+ {
+ if (o1 == null && o2 == null)
+ {
+ return true;
+ }
+ if (o1 == null || o2 == null)
+ {
+ return false;
+ }
+ return o1.equals(o2);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/FileExtensionSelectorTest.java b/trunk/core/src/test/java/org/apache/commons/vfs2/FileExtensionSelectorTest.java
new file mode 100644
index 0000000..47cab77
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/FileExtensionSelectorTest.java
@@ -0,0 +1,180 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+/**
+ * Tests FileExtensionSelector.
+ *
+ * @since 2.1
+ */
+public class FileExtensionSelectorTest
+{
+ private static FileObject BaseFolder;
+
+ private static final int FileCount = 9;
+
+ private static final int ExtensionCount = 3;
+
+ private static final int FilesPerExtensionCount = 3;
+
+ /**
+ * Creates a RAM FS.
+ *
+ * @throws Exception
+ */
+ @BeforeClass
+ public static void setUpClass() throws Exception
+ {
+ BaseFolder = VFS.getManager().resolveFile("ram://" + FileExtensionSelectorTest.class.getName());
+ BaseFolder.deleteAll();
+ BaseFolder.createFolder();
+ BaseFolder.resolveFile("a.htm").createFile();
+ BaseFolder.resolveFile("a.html").createFile();
+ BaseFolder.resolveFile("a.xhtml").createFile();
+ BaseFolder.resolveFile("b.htm").createFile();
+ BaseFolder.resolveFile("b.html").createFile();
+ BaseFolder.resolveFile("b.xhtml").createFile();
+ BaseFolder.resolveFile("c.htm").createFile();
+ BaseFolder.resolveFile("c.html").createFile();
+ BaseFolder.resolveFile("c.xhtml").createFile();
+ }
+
+ /**
+ * Deletes RAM FS files.
+ *
+ * @throws Exception
+ */
+ @AfterClass
+ public static void tearDownClass() throws Exception
+ {
+ if (BaseFolder != null)
+ {
+ BaseFolder.deleteAll();
+ }
+ }
+
+ /**
+ * Tests an empty selector.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testEmpty() throws Exception
+ {
+ final FileSelector selector = new FileExtensionSelector();
+ final FileObject[] foList = BaseFolder.findFiles(selector);
+ Assert.assertEquals(0, foList.length);
+ }
+
+ /**
+ * Tests many extensions at once.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testManyExtensions() throws Exception
+ {
+ final FileObject[] foArray = BaseFolder.findFiles(Selectors.SELECT_FILES);
+ Assert.assertTrue(foArray.length > 0);
+ // gather file extensions.
+ final Set<String> extensionSet = new HashSet<String>();
+ for (final FileObject fo : foArray)
+ {
+ extensionSet.add(fo.getName().getExtension());
+ }
+ final String message = String.format("Extensions: %s; files: %s", extensionSet.toString(),
+ Arrays.asList(foArray).toString());
+ Assert.assertTrue(message, extensionSet.size() > 0);
+ Assert.assertEquals(message, ExtensionCount, extensionSet.size());
+ // check all unique extensions
+ final FileSelector selector = new FileExtensionSelector(extensionSet);
+ final FileObject[] list = BaseFolder.findFiles(selector);
+ Assert.assertEquals(FileCount, list.length);
+ }
+
+ /**
+ * Tests a null selector.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testNullCollection() throws Exception
+ {
+ final FileSelector selector0 = new FileExtensionSelector((Collection<String>) null);
+ final FileObject[] foList = BaseFolder.findFiles(selector0);
+ Assert.assertEquals(0, foList.length);
+ }
+
+ /**
+ * Tests a null selector.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testNullString() throws Exception
+ {
+ final FileSelector selector0 = new FileExtensionSelector((String) null);
+ final FileObject[] foList = BaseFolder.findFiles(selector0);
+ Assert.assertEquals(0, foList.length);
+ }
+
+ /**
+ * Tests a one extension selector.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testOneExtension() throws Exception
+ {
+ final FileObject[] foArray = BaseFolder.findFiles(Selectors.SELECT_FILES);
+ Assert.assertTrue(foArray.length > 0);
+ // gather file extensions.
+ final Set<String> extensionSet = new HashSet<String>();
+ for (final FileObject fo : foArray)
+ {
+ extensionSet.add(fo.getName().getExtension());
+ }
+ final String message = String.format("Extensions: %s; files: %s", extensionSet.toString(),
+ Arrays.asList(foArray).toString());
+ Assert.assertEquals(message, ExtensionCount, extensionSet.size());
+ // check each extension
+ for (final String extension : extensionSet)
+ {
+ final FileSelector selector = new FileExtensionSelector(extension);
+ final FileObject[] list = BaseFolder.findFiles(selector);
+ Assert.assertEquals(FilesPerExtensionCount, list.length);
+ }
+ // check each file against itself
+ for (final FileObject fo : foArray)
+ {
+ final FileSelector selector = new FileExtensionSelector(fo.getName().getExtension());
+ final FileObject[] list = BaseFolder.findFiles(selector);
+ Assert.assertEquals(FilesPerExtensionCount, list.length);
+ }
+ }
+
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/FileIteratorTest.java b/trunk/core/src/test/java/org/apache/commons/vfs2/FileIteratorTest.java
new file mode 100644
index 0000000..38c4a60
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/FileIteratorTest.java
@@ -0,0 +1,99 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+import java.util.Iterator;
+
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+/**
+ * Tests {@link FileObject}s with iterators its implementation the {@link Iterable} interface to allow a FileObject to be the target of the
+ * Java 5 "foreach" statement.
+ */
+public class FileIteratorTest
+{
+
+ private static FileObject BaseFolder;
+
+ private final static int FileCount = 14;
+
+ /**
+ * Creates a RAM FS.
+ *
+ * @throws Exception
+ */
+ @BeforeClass
+ public static void setUpClass() throws Exception
+ {
+ BaseFolder = VFS.getManager().resolveFile("ram://" + FileIteratorTest.class.getName());
+ BaseFolder.deleteAll();
+ BaseFolder.resolveFile("a.htm").createFile();
+ BaseFolder.resolveFile("a.html").createFile();
+ BaseFolder.resolveFile("a.xhtml").createFile();
+ BaseFolder.resolveFile("b.htm").createFile();
+ BaseFolder.resolveFile("b.html").createFile();
+ BaseFolder.resolveFile("b.xhtml").createFile();
+ BaseFolder.resolveFile("c.htm").createFile();
+ BaseFolder.resolveFile("c.html").createFile();
+ BaseFolder.resolveFile("c.xhtml").createFile();
+ BaseFolder.resolveFile("subdir1").createFolder();
+ BaseFolder.resolveFile("subdir1/subfile1.txt").createFile();
+ BaseFolder.resolveFile("subdir2").createFolder();
+ BaseFolder.resolveFile("subdir2/subfile1.txt").createFile();
+ }
+
+ /**
+ * Deletes RAM FS files.
+ *
+ * @throws Exception
+ */
+ @AfterClass
+ public static void tearDownClass() throws Exception
+ {
+ if (BaseFolder != null)
+ {
+ BaseFolder.deleteAll();
+ }
+ }
+
+ @Test
+ public void testIterator() throws FileSystemException
+ {
+ final FileObject[] findFiles = BaseFolder.findFiles(Selectors.SELECT_ALL);
+ Assert.assertEquals(FileCount, findFiles.length);
+ final FileObject[] listFiles = BaseFolder.getChildren();
+ Assert.assertTrue(FileCount > listFiles.length);
+ int i = 0;
+ for (final FileObject actualFile : BaseFolder)
+ {
+ final FileObject expectedFile = findFiles[i];
+ Assert.assertEquals(expectedFile, actualFile);
+ i++;
+ }
+ final Iterator<FileObject> iter = BaseFolder.iterator();
+ i = 0;
+ while (iter.hasNext())
+ {
+ final FileObject expectedFile = findFiles[i];
+ Assert.assertEquals(expectedFile, iter.next());
+ i++;
+ }
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/FileSystemExceptionTest.java b/trunk/core/src/test/java/org/apache/commons/vfs2/FileSystemExceptionTest.java
new file mode 100644
index 0000000..e0e6bb8
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/FileSystemExceptionTest.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+
+/**
+ * Tests the {@link FileSystemException}.
+ */
+public class FileSystemExceptionTest {
+ /**
+ * Tests a {@link FileSystemException} containing info with a URL containing a complete
+ * basic authentication.
+ */
+ @Test
+ public void testMasksPasswordOfUrlsWithBasicAuthentication() {
+ final FileSystemException fse = new FileSystemException(
+ "vfs.provider/rename.error",
+ "file://test.bin", "http://foo:bar@junit.org/test.bin");
+
+ assertEquals("file://test.bin", fse.getInfo()[0]);
+ assertEquals("http://foo:***@junit.org/test.bin", fse.getInfo()[1]);
+ }
+
+ /**
+ * 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
+ public void testProperDetectionOfUrl() {
+ final FileSystemException fse = new FileSystemException(
+ "vfs.provider/delete.error", "zip:http://foo:bar@junit.org/test.bin");
+ assertEquals("zip:http://foo:***@junit.org/test.bin", fse.getInfo()[0]);
+ }
+
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/FileSystemOptionsTest.java b/trunk/core/src/test/java/org/apache/commons/vfs2/FileSystemOptionsTest.java
new file mode 100644
index 0000000..211ec78
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/FileSystemOptionsTest.java
@@ -0,0 +1,85 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * Check FileSystemOptions.
+ *
+ * @since 2.1
+ */
+public class FileSystemOptionsTest {
+
+ @Test
+ public void testEqualsHashCodeAndCompareTo() {
+ final JUnitConfigBuilder builder = JUnitConfigBuilder.getInstance();
+ final FileSystemOptions expected = new FileSystemOptions();
+ builder.setId(expected, "Test");
+
+ final FileSystemOptions actual = new FileSystemOptions();
+ builder.setId(actual, "Test");
+
+ Assert.assertEquals(expected, actual);
+ Assert.assertEquals(0, actual.compareTo(expected));
+ Assert.assertEquals(expected.hashCode(), actual.hashCode());
+
+ builder.setNames(expected, new String[]{"A", "B", "C"});
+
+ Assert.assertNotEquals(expected, actual);
+ Assert.assertEquals(-1, actual.compareTo(expected));
+ Assert.assertNotEquals(expected.hashCode(), actual.hashCode());
+
+ builder.setNames(actual, new String[]{"A", "B", "C"});
+
+ Assert.assertEquals(expected, actual);
+ Assert.assertEquals(0, actual.compareTo(expected));
+ 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/trunk/core/src/test/java/org/apache/commons/vfs2/FileTypeSelectorTest.java b/trunk/core/src/test/java/org/apache/commons/vfs2/FileTypeSelectorTest.java
new file mode 100644
index 0000000..b304b39
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/FileTypeSelectorTest.java
@@ -0,0 +1,90 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+/**
+ * Tests FileTypeSelector.
+ *
+ * @since 2.1
+ */
+public class FileTypeSelectorTest
+{
+ private static FileObject BaseFolder;
+
+ /**
+ * Creates a RAM FS.
+ *
+ * @throws Exception
+ */
+ @BeforeClass
+ public static void setUpClass() throws Exception
+ {
+ BaseFolder = VFS.getManager().resolveFile("ram://" + FileTypeSelectorTest.class.getName());
+ BaseFolder.resolveFile("root1.html").createFile();
+ BaseFolder.resolveFile("root2.html").createFile();
+ BaseFolder.resolveFile("f1/a.html").createFile();
+ BaseFolder.resolveFile("f2/b.html").createFile();
+ BaseFolder.resolveFile("f3/c.html").createFile();
+ BaseFolder.resolveFile("f4/").createFolder();
+ BaseFolder.resolveFile("f5/").createFolder();
+ BaseFolder.resolveFile("f6/f7").createFolder();
+ }
+
+ /**
+ * Deletes RAM FS files.
+ *
+ * @throws Exception
+ */
+ @AfterClass
+ public static void tearDownClass() throws Exception
+ {
+ if (BaseFolder != null)
+ {
+ BaseFolder.deleteAll();
+ }
+ }
+
+ @Test
+ public void testFileOrFolders() throws Exception
+ {
+ final FileSelector selector = new FileTypeSelector(FileType.FILE_OR_FOLDER);
+ final FileObject[] foList = BaseFolder.findFiles(selector);
+ // Why 0?
+ Assert.assertEquals(0, foList.length);
+ }
+
+ @Test
+ public void testFiles() throws Exception
+ {
+ final FileSelector selector = new FileTypeSelector(FileType.FILE);
+ final FileObject[] foList = BaseFolder.findFiles(selector);
+ Assert.assertEquals(5, foList.length);
+ }
+
+ @Test
+ public void testFolders() throws Exception
+ {
+ final FileSelector selector = new FileTypeSelector(FileType.FOLDER);
+ final FileObject[] foList = BaseFolder.findFiles(selector);
+ Assert.assertEquals(8, foList.length);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/FileTypeTest.java b/trunk/core/src/test/java/org/apache/commons/vfs2/FileTypeTest.java
new file mode 100644
index 0000000..f8f22ac
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/FileTypeTest.java
@@ -0,0 +1,82 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+import java.io.Serializable;
+
+import org.apache.commons.lang3.SerializationUtils;
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * Sanity check that a custom enum can be properly serialized and deserialized on a give JRE.
+ *
+ * @since 2.1
+ */
+public class FileTypeTest {
+
+ private static class Fixture implements Serializable {
+ private static final long serialVersionUID = 1L;
+ private final FileType fileType = FileType.FILE;
+
+ public FileType getFileType() {
+ return this.fileType;
+ }
+
+ }
+
+ @Test
+ public void testSerializationFile() {
+ test(FileType.FILE);
+ }
+
+ @Test
+ public void testSerializationContainer() {
+ final Fixture expectedFixture = new Fixture();
+ final byte[] serialized = SerializationUtils.serialize(expectedFixture);
+ final Fixture actualFixture = (Fixture) SerializationUtils.deserialize(serialized);
+ assertEquals(expectedFixture.getFileType(), actualFixture.getFileType());
+ }
+
+ @Test
+ public void testSerializationFileOrFolder() {
+ test(FileType.FILE_OR_FOLDER);
+ }
+
+ @Test
+ public void testSerializationFolder() {
+ test(FileType.FOLDER);
+ }
+
+ @Test
+ 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/trunk/core/src/test/java/org/apache/commons/vfs2/PatternFileSelectorTest.java b/trunk/core/src/test/java/org/apache/commons/vfs2/PatternFileSelectorTest.java
new file mode 100644
index 0000000..6fc2d48
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/PatternFileSelectorTest.java
@@ -0,0 +1,142 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+/**
+ * Tests FileExtensionSelector.
+ *
+ * @since 2.1
+ */
+public class PatternFileSelectorTest
+{
+ private static FileObject BaseFolder;
+
+ /**
+ * 9 files and 1 directory = 10
+ */
+ private static final int EntryCount = 10;
+
+ private static final int ExtensionCount = 3;
+
+ private static final int FilesPerExtensionCount = 3;
+
+ /**
+ * Creates a RAM FS.
+ *
+ * @throws Exception
+ */
+ @BeforeClass
+ public static void setUpClass() throws Exception
+ {
+ BaseFolder = VFS.getManager().resolveFile("ram://" + PatternFileSelectorTest.class.getName());
+ BaseFolder.deleteAll();
+ BaseFolder.createFolder();
+ BaseFolder.resolveFile("a.htm").createFile();
+ BaseFolder.resolveFile("a.html").createFile();
+ BaseFolder.resolveFile("a.xhtml").createFile();
+ BaseFolder.resolveFile("b.htm").createFile();
+ BaseFolder.resolveFile("b.html").createFile();
+ BaseFolder.resolveFile("b.xhtml").createFile();
+ BaseFolder.resolveFile("c.htm").createFile();
+ BaseFolder.resolveFile("c.html").createFile();
+ BaseFolder.resolveFile("c.xhtml").createFile();
+ }
+
+ /**
+ * Deletes RAM FS files.
+ *
+ * @throws Exception
+ */
+ @AfterClass
+ public static void tearDownClass() throws Exception
+ {
+ if (BaseFolder != null)
+ {
+ BaseFolder.deleteAll();
+ }
+ }
+
+ /**
+ * 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(".*"));
+ Assert.assertEquals(EntryCount, list.length);
+ }
+
+ /**
+ * Tests a one extension selector.
+ *
+ * @throws Exception
+ */
+ @Test
+ public void testFileExtensions() throws Exception
+ {
+ final FileObject[] foArray = BaseFolder.findFiles(Selectors.SELECT_FILES);
+ Assert.assertTrue(foArray.length > 0);
+ final String regExPrefix = ".*\\.";
+ // gather file extensions.
+ final Set<String> extensionSet = new HashSet<String>();
+ for (final FileObject fo : foArray)
+ {
+ extensionSet.add(regExPrefix + fo.getName().getExtension());
+ }
+ final String message = String.format("Extensions: %s; files: %s", extensionSet.toString(),
+ Arrays.asList(foArray).toString());
+ Assert.assertEquals(message, ExtensionCount, extensionSet.size());
+ // check each extension
+ for (final String extension : extensionSet)
+ {
+ final FileSelector selector = new PatternFileSelector(extension);
+ final FileObject[] list = BaseFolder.findFiles(selector);
+ Assert.assertEquals(FilesPerExtensionCount, list.length);
+ }
+ // check each file against itself
+ for (final FileObject fo : foArray)
+ {
+ final FileSelector selector = new PatternFileSelector(regExPrefix + fo.getName().getExtension());
+ final FileObject[] list = BaseFolder.findFiles(selector);
+ Assert.assertEquals(FilesPerExtensionCount, list.length);
+ }
+ }
+
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/RunTest.java b/trunk/core/src/test/java/org/apache/commons/vfs2/RunTest.java
new file mode 100644
index 0000000..18a6254
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/RunTest.java
@@ -0,0 +1,119 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+import java.util.Properties;
+
+import junit.framework.AssertionFailedError;
+import junit.framework.Test;
+import junit.framework.TestResult;
+
+public class RunTest
+{
+ public static void main(final String[] args) throws Exception
+ {
+ final String ip = "192.168.0.128";
+
+ final Properties props = System.getProperties();
+ props.setProperty("test.data.src", "src/test-data");
+ props.setProperty("test.basedir", "core/target/test-classes/test-data");
+ props.setProperty("test.basedir.res", "test-data");
+ props.setProperty("test.policy", "src/test-data/test.policy");
+ props.setProperty("test.secure", "false");
+ props.setProperty("test.smb.uri",
+ "smb://HOME\\vfsusr:vfs%2f%25\\te:st@" + ip + "/vfsusr/vfstest");
+ props.setProperty("test.ftp.uri",
+ "ftp://vfsusr:vfs%2f%25\\te:st@" + ip + "/vfstest");
+ props.setProperty("test.ftps.uri",
+ "ftps://vfsusr:vfs%2f%25\\te:st@" + ip + "/vfstest");
+
+ props.setProperty("test.http.uri", "http://" + ip + "/vfstest");
+ props.setProperty("test.webdav.uri",
+ "webdav://vfsusr:vfs%2f%25\\te:st@" + ip + "/vfstest");
+ props.setProperty("test.sftp.uri",
+ "sftp://vfsusr:vfs%2f%25\\te:st@" + ip + "/vfstest");
+
+ final Test tests[] = new Test[]
+ {
+// LocalProviderTestCase.suite(),
+// FtpProviderTestCase.suite(),
+// UrlProviderHttpTestCase.suite(),
+// VirtualProviderTestCase.suite(),
+// TemporaryProviderTestCase.suite(),
+// UrlProviderTestCase.suite(),
+// ResourceProviderTestCase.suite(),
+// HttpProviderTestCase.suite(),
+// SftpProviderTestCase.suite(),
+// JarProviderTestCase.suite(),
+// NestedJarTestCase.suite(),
+// ZipProviderTestCase.suite(),
+// NestedZipTestCase.suite(),
+// TarProviderTestCase.suite(),
+// TgzProviderTestCase.suite(),
+// Tbz2ProviderTestCase.suite(),
+// NestedTarTestCase.suite(),
+// NestedTgzTestCase.suite(),
+// NestedTbz2TestCase.suite(),
+// RamProviderTestCase.suite(),
+
+// SmbProviderTestCase.suite(),
+// WebdavProviderTestCase.suite(),
+ };
+
+ 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();
+ }
+
+ @Override
+ public synchronized void addFailure(final Test test,
+ final AssertionFailedError assertionFailedError)
+ {
+ // throw new RuntimeException(assertionFailedError.getMessage());
+ assertionFailedError.printStackTrace();
+ }
+ };
+
+ for (int i = 0; i < tests.length; i++)
+ {
+ System.out.println("start test#" + i);
+ System.out.flush();
+
+ final Test test = tests[i];
+ test.run(result);
+
+ // break;
+ }
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/UserAuthenticationDataTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/UserAuthenticationDataTestCase.java
new file mode 100644
index 0000000..96f3aeb
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/UserAuthenticationDataTestCase.java
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertSame;
+
+import org.junit.Test;
+
+public class UserAuthenticationDataTestCase
+{
+ @Test
+ public void testCharacterBasedData()
+ {
+ final UserAuthenticationData data = new UserAuthenticationData();
+ final char[] array = "PMC".toCharArray();
+ data.setData(UserAuthenticationData.USERNAME, array);
+ data.setData(UserAuthenticationData.DOMAIN, "Apache".toCharArray());
+ assertSame(array, data.getData(UserAuthenticationData.USERNAME));
+ assertArrayEquals("Apache".toCharArray(), data.getData(UserAuthenticationData.DOMAIN));
+ data.setData(UserAuthenticationData.DOMAIN, "Apache Commons".toCharArray());
+ assertArrayEquals("Apache Commons".toCharArray(), data.getData(UserAuthenticationData.DOMAIN));
+ assertNull(data.getData(UserAuthenticationData.PASSWORD));
+
+ data.cleanup();
+ assertNull(data.getData(UserAuthenticationData.USERNAME));
+ assertNull(data.getData(UserAuthenticationData.DOMAIN));
+ final char[] nulls = {0,0,0};
+ assertArrayEquals(nulls, array);
+ }
+
+ @Test
+ public void testCustomType()
+ {
+ final UserAuthenticationData.Type type = new UserAuthenticationData.Type("JUNIT");
+ final UserAuthenticationData data = new UserAuthenticationData();
+ final char[] array = "test".toCharArray();
+ data.setData(type, array);
+ assertSame(array, data.getData(type));
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/auth/StaticUserAuthenticatorTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/auth/StaticUserAuthenticatorTestCase.java
new file mode 100644
index 0000000..e247549
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/auth/StaticUserAuthenticatorTestCase.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.auth;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertNull;
+
+import org.apache.commons.lang3.ArrayUtils;
+import org.apache.commons.vfs2.UserAuthenticationData;
+import org.apache.commons.vfs2.UserAuthenticator;
+import org.junit.Test;
+
+public class StaticUserAuthenticatorTestCase
+{
+ @Test
+ public void testAuthenticationRequest()
+ {
+ final UserAuthenticator userAuthenticator = new StaticUserAuthenticator("DOMAIN", "USER", "PWD");
+ UserAuthenticationData authenticationData =
+ userAuthenticator.requestAuthentication(ArrayUtils.toArray(UserAuthenticationData.DOMAIN));
+ assertArrayEquals("DOMAIN".toCharArray(), authenticationData.getData(UserAuthenticationData.DOMAIN));
+ assertNull(authenticationData.getData(UserAuthenticationData.USERNAME));
+ assertNull(authenticationData.getData(UserAuthenticationData.PASSWORD));
+ authenticationData = userAuthenticator.requestAuthentication(
+ ArrayUtils.toArray(UserAuthenticationData.USERNAME, UserAuthenticationData.PASSWORD));
+ assertNull(authenticationData.getData(UserAuthenticationData.DOMAIN));
+ assertArrayEquals("USER".toCharArray(), authenticationData.getData(UserAuthenticationData.USERNAME));
+ assertArrayEquals("PWD".toCharArray(), authenticationData.getData(UserAuthenticationData.PASSWORD));
+ }
+
+ @Test
+ public void testEquality()
+ {
+ final UserAuthenticator userAuthenticator = new StaticUserAuthenticator("DOMAIN", "USER", "PWD");
+ assertEquals(new StaticUserAuthenticator("DOMAIN", "USER", "PWD"), userAuthenticator);
+ assertNotEquals(new StaticUserAuthenticator("DOMAIN", "USER", null), userAuthenticator);
+ assertNotEquals(new StaticUserAuthenticator("DOMAIN", null, "PWD"), userAuthenticator);
+ assertNotEquals(new StaticUserAuthenticator(null, "USER", "PWD"), userAuthenticator);
+ assertEquals(new StaticUserAuthenticator("DOMAIN", "USER", "PWD").hashCode(), userAuthenticator.hashCode());
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/cache/DefaultFilesCacheTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/cache/DefaultFilesCacheTestCase.java
new file mode 100644
index 0000000..c59abb3
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/cache/DefaultFilesCacheTestCase.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.cache;
+
+import java.io.File;
+
+import junit.framework.Test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FilesCache;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.CacheTestSuite;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+
+/**
+ * Tests the {@link DefaultFilesCache} using {@link DefaultFilesCacheTests}.
+ */
+public class DefaultFilesCacheTestCase
+ extends AbstractProviderTestConfig
+ implements ProviderTestConfig
+{
+ public static Test suite() throws Exception
+ {
+ final CacheTestSuite suite = new CacheTestSuite(new DefaultFilesCacheTestCase());
+ suite.addTests(DefaultFilesCacheTests.class);
+ return suite;
+ }
+
+ @Override
+ public FilesCache getFilesCache()
+ {
+ return new DefaultFilesCache();
+ }
+
+ @Override
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ final File testDir = AbstractVfsTestCase.getTestDirectoryFile();
+ return manager.toFileObject(testDir);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/cache/DefaultFilesCacheTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/cache/DefaultFilesCacheTests.java
new file mode 100644
index 0000000..22999db
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/cache/DefaultFilesCacheTests.java
@@ -0,0 +1,40 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.cache;
+
+import org.apache.commons.vfs2.FileObject;
+
+/**
+ * Tests for {@link DefaultFilesCache} used by {@link DefaultFilesCacheTestCase}.
+ */
+public class DefaultFilesCacheTests extends FilesCacheTestsBase
+{
+ public void testFilesCache() throws Exception
+ {
+ final FileObject scratchFolder = getWriteFolder();
+
+ final FileObject dir1 = scratchFolder.resolveFile("dir1");
+ final FileObject dir1_2 = scratchFolder.resolveFile("dir1");
+
+ assertSame(dir1, dir1_2);
+
+ // now the same test, unreferenced (compare only hashCode)
+ int hc1 = getFileHashCode();
+ int hc2 = getFileHashCode();
+ assertEquals("Hashcode of file changed, so most likely new instance", hc1, hc2);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/cache/FilesCacheTestsBase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/cache/FilesCacheTestsBase.java
new file mode 100644
index 0000000..20cc13d
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/cache/FilesCacheTestsBase.java
@@ -0,0 +1,93 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.cache;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FilesCache;
+import org.apache.commons.vfs2.test.AbstractProviderTestCase;
+import org.apache.commons.vfs2.test.CacheTestSuite;
+
+/**
+ * Base class for different FilesCache tests.
+ * <p>
+ * Make sure {@link CacheTestSuite} is configured
+ * with correct FilesCache.
+ */
+public class FilesCacheTestsBase 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.
+ */
+ public void testClearFiles() throws Exception
+ {
+ 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");
+
+ assertFalse("Objects after cache clear should be different", fo1 == fo2);
+ }
+
+ /**
+ * Basic Cache operations, work for all caches
+ * (besides {@link NullFilesCache#testBasicCacheOps() NullFilesCache}).
+ */
+ public void testBasicCacheOps() throws Exception
+ {
+ final FilesCache cache = getManager().getFilesCache();
+ final FileObject fo = getWriteFolder().resolveFile("dir1");
+ final FileName fn = fo.getName();
+ final FileSystem fs = fo.getFileSystem();
+
+ cache.clear(fs);
+ assertNull(cache.getFile(fs, fn));
+
+ cache.putFile(fo);
+ assertSame(fo, cache.getFile(fs, fn));
+
+ assertFalse(cache.putFileIfAbsent(fo));
+ cache.clear(fs);
+ assertNull(cache.getFile(fs, fn));
+ assertTrue(cache.putFileIfAbsent(fo));
+
+ cache.removeFile(fs, fn);
+ assertNull(cache.getFile(fs, fn));
+ 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();
+ }
+
+ return fo.hashCode();
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/cache/LRUFilesCacheTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/cache/LRUFilesCacheTestCase.java
new file mode 100644
index 0000000..a34d349
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/cache/LRUFilesCacheTestCase.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.cache;
+
+import java.io.File;
+
+import junit.framework.Test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FilesCache;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.CacheTestSuite;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+
+/**
+ * Tests the {@link LRUFilesCache} using {@link LRUFilesCacheTestss}.
+ */
+public class LRUFilesCacheTestCase
+ extends AbstractProviderTestConfig
+ implements ProviderTestConfig
+{
+ public static Test suite() throws Exception
+ {
+ final CacheTestSuite suite = new CacheTestSuite(new LRUFilesCacheTestCase());
+ suite.addTests(LRUFilesCacheTests.class);
+ return suite;
+ }
+
+ @Override
+ public FilesCache getFilesCache()
+ {
+ return new LRUFilesCache(5);
+ }
+
+ @Override
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ final File testDir = AbstractVfsTestCase.getTestDirectoryFile();
+ return manager.toFileObject(testDir);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/cache/LRUFilesCacheTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/cache/LRUFilesCacheTests.java
new file mode 100644
index 0000000..070ca26
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/cache/LRUFilesCacheTests.java
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.cache;
+
+import org.apache.commons.vfs2.FileObject;
+
+/**
+ * Tests for {@link LRUFilesCache} used by {@link LRUFilesCacheTestCase}.
+ */
+public class LRUFilesCacheTests extends FilesCacheTestsBase
+{
+ public void testFilesCache() throws Exception
+ {
+ final FileObject scratchFolder = getWriteFolder();
+
+ // releaseable
+ final FileObject dir1 = scratchFolder.resolveFile("dir1");
+
+ // avoid cache removal
+ final FileObject dir2 = scratchFolder.resolveFile("dir2");
+ dir2.getContent();
+
+ // releaseable
+ @SuppressWarnings("unused")
+ final
+ FileObject dir3 = scratchFolder.resolveFile("dir3");
+
+ // releaseable
+ @SuppressWarnings("unused")
+ final
+ FileObject dir4 = scratchFolder.resolveFile("dir4");
+
+ // releaseable
+ @SuppressWarnings("unused")
+ final
+ FileObject dir5 = scratchFolder.resolveFile("dir5");
+
+ // releaseable
+ @SuppressWarnings("unused")
+ final
+ FileObject dir6 = scratchFolder.resolveFile("dir6");
+
+ // releaseable
+ @SuppressWarnings("unused")
+ final
+ FileObject dir7 = scratchFolder.resolveFile("dir7");
+
+ // releaseable
+ @SuppressWarnings("unused")
+ final
+ FileObject dir8 = scratchFolder.resolveFile("dir8");
+
+ // check if the cache still holds the right instance
+ final FileObject dir2_2 = scratchFolder.resolveFile("dir2");
+ assertTrue(dir2 == dir2_2);
+
+ // check if the cache still holds the right instance
+ final FileObject dir1_2 = scratchFolder.resolveFile("dir1");
+ assertFalse(dir1 == dir1_2);
+ }
+
+ public void testClass()
+ {
+ assertTrue(getManager().getFilesCache() instanceof LRUFilesCache);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/cache/NullFilesCacheTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/cache/NullFilesCacheTestCase.java
new file mode 100644
index 0000000..60bdb05
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/cache/NullFilesCacheTestCase.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.cache;
+
+import java.io.File;
+
+import junit.framework.Test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FilesCache;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.CacheTestSuite;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+
+/**
+ * Tests the {@link NullFilesCache} using {@link NullFilesCacheTests}.
+ */
+public class NullFilesCacheTestCase
+ extends AbstractProviderTestConfig
+ implements ProviderTestConfig
+{
+ public static Test suite() throws Exception
+ {
+ final CacheTestSuite suite = new CacheTestSuite(new NullFilesCacheTestCase());
+ suite.addTests(NullFilesCacheTests.class);
+ return suite;
+ }
+
+ @Override
+ public FilesCache getFilesCache()
+ {
+ return new NullFilesCache();
+ }
+
+ @Override
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ final File testDir = AbstractVfsTestCase.getTestDirectoryFile();
+ return manager.toFileObject(testDir);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/cache/NullFilesCacheTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/cache/NullFilesCacheTests.java
new file mode 100644
index 0000000..cf2e48d
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/cache/NullFilesCacheTests.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.cache;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FilesCache;
+
+/**
+ * Tests for {@link NullFilesCache} used by {@link NullFilesCacheTestCase}.
+ */
+public class NullFilesCacheTests extends FilesCacheTestsBase
+{
+ public void testFilesCache() throws Exception
+ {
+ final FileObject scratchFolder = getWriteFolder();
+
+ final FileObject dir1 = scratchFolder.resolveFile("dir1");
+ final FileObject dir1_2 = scratchFolder.resolveFile("dir1");
+
+ assertFalse("Should always be new instance with NullCache", dir1 == dir1_2);
+ }
+
+ @Override
+ public void testBasicCacheOps() throws Exception
+ {
+ // the basic test looks different for a null cache:
+
+ final FilesCache cache = getManager().getFilesCache();
+ final FileObject fo = getWriteFolder().resolveFile("dir1");
+ final FileName fn = fo.getName();
+ final FileSystem fs = fo.getFileSystem();
+
+ cache.clear(fs);
+ assertNull(cache.getFile(fs, fn));
+
+ cache.putFile(fo);
+ assertNull(null, cache.getFile(fs, fn));
+
+ assertFalse(cache.putFileIfAbsent(fo)); // hmmm?
+ assertNull(null, cache.getFile(fs, fn));
+
+ cache.removeFile(fs, fn);
+ assertNull(cache.getFile(fs, fn));
+ }
+
+
+ public void testClass()
+ {
+ assertTrue(getManager().getFilesCache() instanceof NullFilesCache);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/cache/SoftRefFilesCacheTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/cache/SoftRefFilesCacheTestCase.java
new file mode 100644
index 0000000..788dcf4
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/cache/SoftRefFilesCacheTestCase.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.cache;
+
+import java.io.File;
+
+import junit.framework.Test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FilesCache;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.CacheTestSuite;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+
+/**
+ * Tests the {@link SoftRefFilesCache} using {@link SoftRefFilesCacheTests}.
+ */
+public class SoftRefFilesCacheTestCase
+ extends AbstractProviderTestConfig
+ implements ProviderTestConfig
+{
+ public static Test suite() throws Exception
+ {
+ final CacheTestSuite suite = new CacheTestSuite(new SoftRefFilesCacheTestCase());
+ suite.addTests(SoftRefFilesCacheTests.class);
+ return suite;
+ }
+
+ @Override
+ public FilesCache getFilesCache()
+ {
+ return new SoftRefFilesCache();
+ }
+
+ @Override
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ final File testDir = AbstractVfsTestCase.getTestDirectoryFile();
+ return manager.toFileObject(testDir);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/cache/SoftRefFilesCacheTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/cache/SoftRefFilesCacheTests.java
new file mode 100644
index 0000000..23cd366
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/cache/SoftRefFilesCacheTests.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.cache;
+
+import org.apache.commons.vfs2.FileObject;
+
+/**
+ * Tests for {@link SoftRefFilesCache} used by {@link SoftRefFilesCacheTestCase}.
+ */
+public class SoftRefFilesCacheTests extends FilesCacheTestsBase
+{
+ public void testFilesCache() throws Exception
+ {
+ final FileObject scratchFolder = getWriteFolder();
+
+ final FileObject dir1 = scratchFolder.resolveFile("dir1");
+ final FileObject dir1_2 = scratchFolder.resolveFile("dir1");
+
+ // since both are still referenced they are not purged
+ assertSame(dir1, dir1_2);
+ }
+
+ public void testClass()
+ {
+ assertTrue(getManager().getFilesCache() instanceof SoftRefFilesCache);
+ }
+
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/cache/WeakRefFilesCacheTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/cache/WeakRefFilesCacheTestCase.java
new file mode 100644
index 0000000..01882f9
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/cache/WeakRefFilesCacheTestCase.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.cache;
+
+import java.io.File;
+
+import junit.framework.Test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FilesCache;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.CacheTestSuite;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+
+/**
+ * Tests the {@link WeakRefFilesCache} using {@link WeakRefFilesCacheTests}.
+ */
+public class WeakRefFilesCacheTestCase
+ extends AbstractProviderTestConfig
+ implements ProviderTestConfig
+{
+ public static Test suite() throws Exception
+ {
+ final CacheTestSuite suite = new CacheTestSuite(new WeakRefFilesCacheTestCase());
+ suite.addTests(WeakRefFilesCacheTests.class);
+ return suite;
+ }
+
+ @Override
+ public FilesCache getFilesCache()
+ {
+ return new WeakRefFilesCache();
+ }
+
+ @Override
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ final File testDir = AbstractVfsTestCase.getTestDirectoryFile();
+ return manager.toFileObject(testDir);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/cache/WeakRefFilesCacheTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/cache/WeakRefFilesCacheTests.java
new file mode 100644
index 0000000..f0ef1c6
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/cache/WeakRefFilesCacheTests.java
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.cache;
+
+import org.apache.commons.vfs2.FileObject;
+
+/**
+ * Tests for {@link WeakRefFilesCache} used by {@link WeakRefFilesCacheTestCase}.
+ */
+public class WeakRefFilesCacheTests extends FilesCacheTestsBase
+{
+ public void testFilesCache() throws Exception
+ {
+ final FileObject scratchFolder = getWriteFolder();
+
+ final FileObject dir1 = scratchFolder.resolveFile("dir1");
+ final FileObject dir1_2 = scratchFolder.resolveFile("dir1");
+
+ // since both are still referenced they are not purged
+ assertSame(dir1, dir1_2);
+ }
+
+ public void testClass()
+ {
+ assertTrue(getManager().getFilesCache() instanceof WeakRefFilesCache);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/impl/test/DefaultFileMonitorTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/impl/test/DefaultFileMonitorTests.java
new file mode 100644
index 0000000..9325a34
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/impl/test/DefaultFileMonitorTests.java
@@ -0,0 +1,217 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.impl.test;
+
+import java.io.File;
+import java.io.FileWriter;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileChangeEvent;
+import org.apache.commons.vfs2.FileListener;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.VFS;
+import org.apache.commons.vfs2.impl.DefaultFileMonitor;
+
+/**
+ * Test to verify DefaultFileMonitor
+ */
+public class DefaultFileMonitorTests extends AbstractVfsTestCase
+{
+ private FileSystemManager fsManager;
+ private File testDir;
+ private int changeStatus = 0;
+ private File testFile;
+
+ @Override
+ public void setUp() throws Exception
+ {
+ super.setUp();
+ fsManager = VFS.getManager();
+ testDir = AbstractVfsTestCase.getTestDirectoryFile();
+ changeStatus = 0;
+ testFile = new File(testDir, "testReload.properties");
+
+ if (testFile.exists())
+ {
+ testFile.delete();
+ }
+ }
+
+ @Override
+ public void tearDown() throws Exception
+ {
+ if (testFile != null && testFile.exists())
+ {
+ testFile.delete();
+ }
+ super.tearDown();
+ }
+
+ public void testFileCreated() throws Exception
+ {
+ final FileObject fileObj = fsManager.resolveFile(testFile.toURI().toURL().toString());
+ final DefaultFileMonitor monitor = new DefaultFileMonitor(new TestFileListener());
+ // TestFileListener manipulates changeStatus
+ monitor.setDelay(100);
+ monitor.addFile(fileObj);
+ monitor.start();
+ try
+ {
+ writeToFile(testFile);
+ Thread.sleep(300);
+ assertTrue("No event occurred", changeStatus != 0);
+ assertTrue("Incorrect event", changeStatus == 3);
+ } finally {
+ monitor.stop();
+ }
+ }
+
+ public void testFileDeleted() throws Exception
+ {
+ writeToFile(testFile);
+ final FileObject fileObj = fsManager.resolveFile(testFile.toURI().toString());
+ final DefaultFileMonitor monitor = new DefaultFileMonitor(new TestFileListener());
+ // TestFileListener manipulates changeStatus
+ monitor.setDelay(100);
+ monitor.addFile(fileObj);
+ monitor.start();
+ try
+ {
+ testFile.delete();
+ Thread.sleep(300);
+ assertTrue("No event occurred", changeStatus != 0);
+ assertTrue("Incorrect event", changeStatus == 2);
+ } finally {
+ monitor.stop();
+ }
+ }
+
+ public void testFileModified() throws Exception
+ {
+ writeToFile(testFile);
+ final FileObject fileObj = fsManager.resolveFile(testFile.toURI().toURL().toString());
+ final DefaultFileMonitor monitor = new DefaultFileMonitor(new TestFileListener());
+ // TestFileListener manipulates changeStatus
+ monitor.setDelay(100);
+ monitor.addFile(fileObj);
+ monitor.start();
+ try
+ {
+ // Need a long delay to insure the new timestamp doesn't truncate to be the same as
+ // the current timestammp. Java only guarantees the timestamp will be to 1 second.
+ Thread.sleep(1000);
+ final long value = System.currentTimeMillis();
+ final boolean rc = testFile.setLastModified(value);
+ assertTrue("setLastModified succeeded",rc);
+ Thread.sleep(300);
+ assertTrue("No event occurred", changeStatus != 0);
+ assertTrue("Incorrect event", changeStatus == 1);
+ } finally {
+ monitor.stop();
+ }
+ }
+
+
+ public void testFileRecreated() throws Exception
+ {
+ final FileObject fileObj = fsManager.resolveFile(testFile.toURI().toURL().toString());
+ final DefaultFileMonitor monitor = new DefaultFileMonitor(new TestFileListener());
+ // TestFileListener manipulates changeStatus
+ monitor.setDelay(100);
+ monitor.addFile(fileObj);
+ monitor.start();
+ try
+ {
+ writeToFile(testFile);
+ Thread.sleep(300);
+ assertTrue("No event occurred", changeStatus != 0);
+ assertTrue("Incorrect event " + changeStatus, changeStatus == 3);
+ changeStatus = 0;
+ testFile.delete();
+ Thread.sleep(300);
+ assertTrue("No event occurred", changeStatus != 0);
+ assertTrue("Incorrect event " + changeStatus, changeStatus == 2);
+ changeStatus = 0;
+ Thread.sleep(500);
+ monitor.addFile(fileObj);
+ writeToFile(testFile);
+ Thread.sleep(300);
+ assertTrue("No event occurred", changeStatus != 0);
+ assertTrue("Incorrect event " + changeStatus, changeStatus == 3);
+ } finally {
+ monitor.stop();
+ }
+ }
+
+ public void testChildFileRecreated() throws Exception
+ {
+ writeToFile(testFile);
+ final FileObject fileObj = fsManager.resolveFile(testDir.toURI().toURL().toString());
+ final DefaultFileMonitor monitor = new DefaultFileMonitor(new TestFileListener());
+ monitor.setDelay(2000);
+ monitor.addFile(fileObj);
+ monitor.start();
+ try
+ {
+ changeStatus = 0;
+ Thread.sleep(300);
+ testFile.delete();
+ Thread.sleep(3000);
+ assertTrue("No event occurred", changeStatus != 0);
+ assertTrue("Incorrect event " + changeStatus, changeStatus == 2);
+ changeStatus = 0;
+ Thread.sleep(300);
+ writeToFile(testFile);
+ Thread.sleep(3000);
+ assertTrue("No event occurred", changeStatus != 0);
+ assertTrue("Incorrect event " + changeStatus, changeStatus == 3);
+ } finally {
+ monitor.stop();
+ }
+ }
+
+ private void writeToFile(final File file) throws Exception
+ {
+ final FileWriter out = new FileWriter(file);
+ out.write("string=value1");
+ out.close();
+ }
+
+
+ public class TestFileListener implements FileListener
+ {
+ @Override
+ public void fileChanged(final FileChangeEvent event) throws Exception
+ {
+ changeStatus = 1;
+ }
+
+ @Override
+ public void fileDeleted(final FileChangeEvent event) throws Exception
+ {
+ changeStatus = 2;
+ }
+
+ @Override
+ public void fileCreated(final FileChangeEvent event) throws Exception
+ {
+ changeStatus = 3;
+ }
+ }
+
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/impl/test/DefaultFileSystemManagerTest.java b/trunk/core/src/test/java/org/apache/commons/vfs2/impl/test/DefaultFileSystemManagerTest.java
new file mode 100644
index 0000000..4c9affa
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/impl/test/DefaultFileSystemManagerTest.java
@@ -0,0 +1,59 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.impl.test;
+
+import java.io.File;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.VFS;
+import org.junit.Test;
+
+public class DefaultFileSystemManagerTest
+{
+ @Test(expected = NullPointerException.class)
+ public void testResolveFileRelativeThrows() throws FileSystemException
+ {
+ VFS.getManager().resolveFile((File) null, "relativePath");
+ }
+
+ /**
+ * Even if the file name is absolute, the base file must be given. This is
+ * an inconsistency in the API, but it is documented as such.
+ *
+ * @see "VFS-519"
+ */
+ @Test(expected = NullPointerException.class)
+ public void testResolveFileAbsoluteThrows() throws FileSystemException
+ {
+ String absolute = new File("/").getAbsoluteFile().toURI().toString();
+ VFS.getManager().resolveFile((File) null, absolute);
+ }
+
+ @Test(expected = FileSystemException.class)
+ public void testResolveFileObjectRelativeThrows() throws FileSystemException
+ {
+ VFS.getManager().resolveFile((FileObject) null, "relativePath");
+ }
+
+ @Test
+ public void testResolveFileObjectNullAbsolute() throws FileSystemException
+ {
+ String absolute = new File("/").getAbsoluteFile().toURI().toString();
+ VFS.getManager().resolveFile((FileObject) null, absolute);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/impl/test/VfsClassLoaderTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/impl/test/VfsClassLoaderTests.java
new file mode 100644
index 0000000..84a4af3
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/impl/test/VfsClassLoaderTests.java
@@ -0,0 +1,254 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.impl.test;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.util.Collections;
+import java.util.Enumeration;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.impl.VFSClassLoader;
+import org.apache.commons.vfs2.test.AbstractProviderTestCase;
+
+/**
+ * VfsClassLoader test cases.
+ */
+public class VfsClassLoaderTests
+ extends AbstractProviderTestCase
+{
+ /**
+ * Returns the capabilities required by the tests of this test case.
+ */
+ @Override
+ protected Capability[] getRequiredCaps()
+ {
+ return new Capability[]
+ {
+ Capability.READ_CONTENT,
+ Capability.URI
+ };
+ }
+
+ /**
+ * Creates the classloader to use when testing.
+ */
+ private VFSClassLoader createClassLoader() throws FileSystemException
+ {
+ final FileObject file = getBaseFolder();
+ return new VFSClassLoader(file, getManager());
+ }
+
+ /**
+ * Tests loading a class.
+ */
+ 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.
+ */
+ 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.
+ */
+ 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);
+ }
+
+ /**
+ * Tests retrieving resources (from JAR searchpath).
+ * <p>
+ * This is run for all providers, but only when a local
+ * provider is present and jar extension is registered
+ * it will actually carry out all tests.
+ */
+ public void testGetResourcesJARs() throws Exception
+ {
+ final FileSystemManager manager = getManager();
+ try
+ {
+ // hasProvider("file") cannot be used as it triggers default provider URL
+ manager.toFileObject(new File("."));
+ }
+ catch (FileSystemException e)
+ {
+ System.out.println("VfsClassLoaderTests no local file provider, skipping.");
+ return;
+ }
+
+ // build search path without using #getBaseFolder()
+ // because NestedJarTestCase redefines it
+ final File baseDir = AbstractVfsTestCase.getTestDirectoryFile();
+ final FileObject nestedJar = manager.resolveFile(baseDir, "nested.jar");
+ final FileObject testJar = manager.resolveFile(baseDir, "test.jar");
+
+ // test setup needs to know about .jar extension - i.e. NestedJarTestCase
+ if (!manager.canCreateFileSystem(nestedJar))
+ {
+ System.out.println("VfsClassLoaderTests no layered .jar provider, skipping.");
+ return;
+ }
+
+ // verify test setup
+ assertTrue("nested.jar is required for testing", nestedJar.getType() == FileType.FILE);
+ assertTrue("test.jar is required for testing", testJar.getType() == FileType.FILE);
+
+ // System class loader (null) might be unpredictable in regards
+ // to returning resources for META-INF/MANIFEST.MF (see VFS-500)
+ // so we use our own which is guaranteed to not return any hit
+ final ClassLoader mockClassloader = new MockClassloader();
+ final FileObject[] search = new FileObject[] { nestedJar, testJar };
+ final VFSClassLoader loader = new VFSClassLoader(search, getManager(), mockClassloader);
+
+ final Enumeration<URL> urls = loader.getResources("META-INF/MANIFEST.MF");
+ final URL url1 = urls.nextElement();
+ final URL url2 = urls.nextElement();
+
+ assertTrue("First resource must refer to nested.jar but was " + url1, url1.toString().endsWith("nested.jar!/META-INF/MANIFEST.MF"));
+ assertTrue("Second resource must refer to test.jar but was " + url2, url2.toString().endsWith("test.jar!/META-INF/MANIFEST.MF"));
+ }
+
+ /**
+ * Tests retrieving resources (from local directory with .jar extension).
+ * <p>
+ * This test is repeated with various provider configurations but works on local files, only.
+ */
+ public void testGetResourcesNoLayerLocal() throws Exception
+ {
+ final FileSystemManager manager = getManager();
+ try
+ {
+ // hasProvider("file") cannot be used as it triggers default provider URL
+ manager.toFileObject(new File("."));
+ }
+ catch (FileSystemException e)
+ {
+ System.out.println("VfsClassLoaderTests no local file provider, skipping.");
+ return;
+ }
+ final File baseDir = AbstractVfsTestCase.getTestDirectoryFile();
+
+ // setup test folder
+ final FileObject dir = manager.resolveFile(baseDir, "read-tests/dir1/subdir4.jar");
+ assertTrue("subdir4.jar/ is required for testing " + dir, dir.getType() == FileType.FOLDER);
+ assertFalse(manager.canCreateFileSystem(dir));
+
+ // prepare classloader
+ final FileObject[] search = new FileObject[] { dir };
+ final ClassLoader mockClassloader = new MockClassloader();
+ final VFSClassLoader loader = new VFSClassLoader(search, getManager(), mockClassloader);
+
+ // verify resource loading
+ final Enumeration<URL> urls = loader.getResources("file1.txt");
+ final URL url1 = urls.nextElement();
+ assertFalse("Only one hit expected", urls.hasMoreElements());
+ assertTrue("not pointing to resource " + url1, url1.toString().endsWith("subdir4.jar/file1.txt"));
+ }
+
+
+ /**
+ * Verify the package loaded with class loader.
+ */
+ private void verifyPackage(final Package pack,
+ final boolean sealed)
+ {
+ if (getBaseFolder().getFileSystem().hasCapability(Capability.MANIFEST_ATTRIBUTES))
+ {
+ assertEquals("ImplTitle", pack.getImplementationTitle());
+ assertEquals("ImplVendor", pack.getImplementationVendor());
+ assertEquals("1.1", pack.getImplementationVersion());
+ assertEquals("SpecTitle", pack.getSpecificationTitle());
+ assertEquals("SpecVendor", pack.getSpecificationVendor());
+ assertEquals("1.0", pack.getSpecificationVersion());
+ assertEquals(sealed, pack.isSealed());
+ }
+ else
+ {
+ assertNull(pack.getImplementationTitle());
+ assertNull(pack.getImplementationVendor());
+ assertNull(pack.getImplementationVersion());
+ assertNull(pack.getSpecificationTitle());
+ assertNull(pack.getSpecificationVendor());
+ assertNull(pack.getSpecificationVersion());
+ 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(String name)
+ throws IOException
+ {
+ return Collections.enumeration(Collections.<URL> emptyList());
+ }
+
+ @Override
+ protected Class<?> findClass(String name)
+ throws ClassNotFoundException
+ {
+ fail("Not intended to be used for class loading.");
+ return null;
+ }
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/operations/BasicOperationsTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/operations/BasicOperationsTestCase.java
new file mode 100644
index 0000000..c514ce6
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/operations/BasicOperationsTestCase.java
@@ -0,0 +1,217 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.operations;
+
+import static org.junit.Assert.*;
+
+import java.io.File;
+import java.util.Collection;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.operations.vcs.VcsLog;
+import org.apache.commons.vfs2.provider.FileProvider;
+import org.apache.commons.vfs2.provider.VfsComponent;
+import org.apache.commons.vfs2.provider.VfsComponentContext;
+import org.apache.commons.vfs2.provider.local.DefaultLocalFileProvider;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * Basic Tests for the FileOperations and FileOperationsProvider API.
+ */
+public class BasicOperationsTestCase
+{
+ /** This FileOperationsProvider is a VfsComponent and records invocations. */
+ static class MyFileOperationProviderComp
+ extends MyFileOprationProviderBase
+ implements VfsComponent
+ {
+ @Override
+ public void setLogger(Log logger)
+ {
+ assertNotNull("setLogger", logger);
+ ops |= 1;
+ }
+
+ @Override
+ public void setContext(VfsComponentContext context)
+ {
+ assertNotNull("setContext", context);
+ ops |= 2;
+ }
+
+ @Override
+ public void init()
+ throws FileSystemException
+ {
+ ops |= 4;
+ }
+
+ @Override
+ public void close()
+ {
+ ops |= 8;
+ }
+ }
+
+ /** This FileOperationsProvider is no VfsComponent. */
+ static class MyFileOperationProviderNoncomp
+ extends MyFileOprationProviderBase
+ {
+ }
+
+ /**
+ * Base class for different Test Providers. This is also a compile test
+ * to ensure interface stability.
+ */
+ static class MyFileOprationProviderBase implements FileOperationProvider
+ {
+ int ops = 0; // bit array to record invocations (poor mans mock)
+
+ @Override
+ public void collectOperations(Collection<Class< ? extends FileOperation>> operationsList,
+ FileObject file)
+ throws FileSystemException
+ {
+ assertNotNull("collect operationsList", operationsList);
+ assertNotNull("collect file", file);
+ ops |= 16;
+ }
+
+ @Override
+ public FileOperation getOperation(FileObject file, Class< ? extends FileOperation> operationClass)
+ throws FileSystemException
+ {
+ assertNotNull("file object", file);
+ assertNotNull("operationclass", operationClass);
+ ops |= 32;
+ return null;
+ }
+ }
+
+ /** FSM to work with, maintained by JUnit Fixture. */
+ private DefaultFileSystemManager manager;
+
+ /**
+ * JUnit Fixture: Prepare a simple FSM.
+ * @throws FileSystemException for runtime problems
+ */
+ @Before
+ public void setUp() throws FileSystemException
+ {
+ manager = new DefaultFileSystemManager();
+ FileProvider fp = new DefaultLocalFileProvider();
+ manager.addProvider("file", fp);
+ manager.init();
+ }
+
+ /**
+ * Ensure FileOperationProviders which are VfsComponents are
+ * set up and teared down.
+ * @throws FileSystemException for runtime problems
+ */
+ @Test
+ public void testLifecycleComp() throws FileSystemException
+ {
+ final MyFileOprationProviderBase myop = new MyFileOperationProviderComp();
+ assertEquals(0, myop.ops);
+ manager.addOperationProvider("file", myop);
+ assertEquals(7, myop.ops);
+ manager.close();
+ assertEquals("close() not called", 15, myop.ops); // VFS-577
+
+ //fixture will close again
+ }
+
+ /**
+ * Ensure you can use FileOperationProvider which is not a VfsComponnt.
+ * @throws FileSystemException for runtime problems
+ */
+ @Test
+ public void testLifecycleNoncomp() throws FileSystemException
+ {
+ final MyFileOprationProviderBase myop = new MyFileOperationProviderNoncomp();
+ manager.addOperationProvider("file", myop);
+ FileOperationProvider[] ops = manager.getOperationProviders("file");
+ assertSame("exactly one provider registered", 1, ops.length);
+ assertSame(myop, ops[0]);
+ assertEquals(0, myop.ops); // collect not invoked
+ }
+
+ /**
+ * Ensures getOperations calls collect and allows empty response.
+ * @throws FileSystemException for runtime problems
+ */
+ @Test
+ public void testNotFoundAny() throws FileSystemException
+ {
+ final MyFileOprationProviderBase myop = new MyFileOperationProviderNoncomp();
+ manager.addOperationProvider("file", myop);
+ FileObject fo = manager.toFileObject(new File("."));
+
+ FileOperations ops = fo.getFileOperations();
+ assertNotNull(ops);
+
+ Class< ? extends FileOperation>[] oparray = ops.getOperations();
+ assertSame("no ops should be found", 0, oparray.length);
+ assertSame(16, myop.ops); // collect
+ }
+
+ /**
+ * Ensure proper response for not found FileOperation.
+ * @throws FileSystemException for runtime problems
+ */
+ @Test
+ public void testNotFoundOperation() throws FileSystemException
+ {
+ final MyFileOprationProviderBase myop = new MyFileOperationProviderNoncomp();
+ manager.addOperationProvider("file", myop);
+ FileObject fo = manager.toFileObject(new File("."));
+
+ FileOperations ops = fo.getFileOperations();
+ assertNotNull(ops);
+
+ try
+ {
+ FileOperation logop = ops.getOperation(VcsLog.class);
+ fail("Must throw but returned " + logop);
+ }
+ catch (FileSystemException e)
+ {
+ assertEquals("vfs.operation/operation-not-supported.error", e.getCode());
+ }
+ 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/trunk/core/src/test/java/org/apache/commons/vfs2/perf/FileNamePerformance.java b/trunk/core/src/test/java/org/apache/commons/vfs2/perf/FileNamePerformance.java
new file mode 100644
index 0000000..8884077
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/perf/FileNamePerformance.java
@@ -0,0 +1,102 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.perf;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.VFS;
+
+public class FileNamePerformance
+{
+ private final static int NUOF_RESOLVES = 100000;
+
+ public static void main(final String[] args) throws FileSystemException
+ {
+ final FileSystemManager mgr = VFS.getManager();
+
+ final FileObject root = mgr
+ .resolveFile("smb://HOME\\vfsusr:vfs%2f%25\\te:st@10.0.1.54/vfsusr");
+ final FileName rootName = root.getName();
+
+ testNames(mgr, rootName);
+
+ testChildren(root);
+
+ testFiles(mgr);
+ }
+
+ private static void testFiles(final FileSystemManager mgr) 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");
+ }
+
+ final long start = 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");
+ }
+ final long end = System.currentTimeMillis();
+
+ System.err.println("time to resolve " + NUOF_RESOLVES + " files: "
+ + (end - start) + "ms");
+ }
+
+ private static void testChildren(final FileObject root) throws FileSystemException
+ {
+ for (int i = 0; i < 10; i++)
+ {
+ // warmup jvm
+ root.resolveFile("/many/path/elements/with%25esc/any%25where/to/file.txt");
+ }
+
+ final long start = System.currentTimeMillis();
+ for (int i = 0; i < NUOF_RESOLVES; i++)
+ {
+ root.resolveFile("/many/path/elements/with%25esc/any%25where/to/file.txt");
+ }
+ final long end = System.currentTimeMillis();
+
+ System.err.println("time to resolve " + NUOF_RESOLVES + " children: "
+ + (end - start) + "ms");
+ }
+
+ private static void testNames(final FileSystemManager mgr, final FileName rootName) throws FileSystemException
+ {
+ for (int i = 0; i < 10; i++)
+ {
+ // warmup jvm
+ mgr.resolveName(rootName,
+ "/many/path/elements/with%25esc/any%25where/to/file.txt");
+ }
+
+ final long start = System.currentTimeMillis();
+ for (int i = 0; i < NUOF_RESOLVES; i++)
+ {
+ mgr.resolveName(rootName,
+ "/many/path/elements/with%25esc/any%25where/to/file.txt");
+ }
+ final long end = System.currentTimeMillis();
+
+ System.err.println("time to resolve " + NUOF_RESOLVES + " names: "
+ + (end - start) + "ms");
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/UriParserTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/UriParserTestCase.java
new file mode 100644
index 0000000..4dfe39c
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/UriParserTestCase.java
@@ -0,0 +1,41 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider;
+
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ *
+ * @version $Id$
+ */
+public class UriParserTestCase
+{
+
+ @Test
+ public void testColonInFileName()
+ {
+ Assert.assertEquals(null, UriParser.extractScheme("some/path/some:file"));
+ }
+
+ @Test
+ public void testNormalScheme()
+ {
+ Assert.assertEquals("ftp", UriParser.extractScheme("ftp://user:pass@host/some/path/some:file"));
+ }
+
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ftp/test/FtpProviderTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ftp/test/FtpProviderTestCase.java
new file mode 100644
index 0000000..a9489ea
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ftp/test/FtpProviderTestCase.java
@@ -0,0 +1,195 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ftp.test;
+
+import java.io.IOException;
+import java.net.URL;
+
+import junit.framework.Test;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.ftp.FtpFileProvider;
+import org.apache.commons.vfs2.provider.ftp.FtpFileSystemConfigBuilder;
+import org.apache.commons.vfs2.provider.ftp.FtpFileType;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+import org.apache.commons.vfs2.util.FreeSocketPortUtil;
+import org.apache.ftpserver.FtpServer;
+import org.apache.ftpserver.FtpServerFactory;
+import org.apache.ftpserver.ftplet.FtpException;
+import org.apache.ftpserver.ftplet.UserManager;
+import org.apache.ftpserver.listener.ListenerFactory;
+import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
+import org.apache.ftpserver.usermanager.impl.BaseUser;
+import org.junit.Assert;
+
+/**
+ * Tests for FTP file systems.
+ */
+public class FtpProviderTestCase extends AbstractProviderTestConfig implements ProviderTestConfig
+{
+ private static int SocketPort;
+
+ /**
+ * Use %40 for @ in URLs
+ */
+ private static String ConnectionUri;
+
+ private static FtpServer Server;
+
+ private static final String TEST_URI = "test.ftp.uri";
+
+ private static final String USER_PROPS_RES = "org.apache.ftpserver/users.properties";
+
+ static String getConnectionUri()
+ {
+ return ConnectionUri;
+ }
+
+ static int getSocketPort()
+ {
+ return SocketPort;
+ }
+
+ private static String getSystemTestUriOverride()
+ {
+ return System.getProperty(TEST_URI);
+ }
+
+ static void init() throws IOException
+ {
+ SocketPort = FreeSocketPortUtil.findFreeLocalPort();
+ // Use %40 for @ in a URL
+ ConnectionUri = "ftp://test:test@localhost:" + SocketPort;
+ }
+
+ /**
+ * Creates and starts an embedded Apache FTP Server (MINA).
+ *
+ * @throws FtpException
+ * @throws IOException
+ */
+ static void setUpClass() throws FtpException, IOException
+ {
+ if (Server != null)
+ {
+ return;
+ }
+ init();
+ final FtpServerFactory serverFactory = new FtpServerFactory();
+ final PropertiesUserManagerFactory propertiesUserManagerFactory = new PropertiesUserManagerFactory();
+ final URL userPropsResource = ClassLoader.getSystemClassLoader().getResource(USER_PROPS_RES);
+ Assert.assertNotNull(USER_PROPS_RES, userPropsResource);
+ propertiesUserManagerFactory.setUrl(userPropsResource);
+ final UserManager userManager = propertiesUserManagerFactory.createUserManager();
+ final BaseUser user = (BaseUser) userManager.getUserByName("test");
+ // Pickup the home dir value at runtime even though we have it set in the user prop file
+ // The user prop file requires the "homedirectory" to be set
+ user.setHomeDirectory(getTestDirectory());
+ serverFactory.setUserManager(userManager);
+ final ListenerFactory factory = new ListenerFactory();
+ // set the port of the listener
+ factory.setPort(SocketPort);
+
+ // replace the default listener
+ serverFactory.addListener("default", factory.createListener());
+
+ // start the server
+ Server = serverFactory.createServer();
+ Server.start();
+ }
+
+ /**
+ * Creates the test suite for the ftp file system.
+ */
+ public static Test suite() throws Exception
+ {
+ return new ProviderTestSuite(new FtpProviderTestCase())
+ {
+ @Override
+ protected void setUp() throws Exception
+ {
+ if (getSystemTestUriOverride() == null)
+ {
+ setUpClass();
+ }
+ 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();
+ }
+ }
+ };
+ }
+
+ /**
+ * Stops the embedded Apache FTP Server (MINA).
+ */
+ static void tearDownClass()
+ {
+ if (Server != null)
+ {
+ Server.stop();
+ Server = null;
+ }
+ }
+
+ /**
+ * Returns the base folder for tests. You can override the DEFAULT_URI by using the system property name defined by
+ * TEST_URI.
+ */
+ @Override
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ String uri = getSystemTestUriOverride();
+ if (uri == null)
+ {
+ uri = ConnectionUri;
+ }
+ final FileSystemOptions opts = new FileSystemOptions();
+ final FtpFileSystemConfigBuilder builder = FtpFileSystemConfigBuilder.getInstance();
+ builder.setPassiveMode(opts, true);
+ // FtpFileType.BINARY is the default
+ builder.setFileType(opts, FtpFileType.BINARY);
+ builder.setConnectTimeout(opts, 10000);
+ builder.setControlEncoding(opts, "UTF-8");
+ return manager.resolveFile(uri, opts);
+ }
+
+ /**
+ * Prepares the file system manager.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager) throws Exception
+ {
+ manager.addProvider("ftp", new FtpFileProvider());
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ftp/test/MultipleConnectionTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ftp/test/MultipleConnectionTestCase.java
new file mode 100644
index 0000000..3076350
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ftp/test/MultipleConnectionTestCase.java
@@ -0,0 +1,81 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ftp.test;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.SocketException;
+
+import org.apache.commons.net.ftp.FTPClient;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.VFS;
+import org.apache.ftpserver.ftplet.FtpException;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class MultipleConnectionTestCase
+{
+
+ @BeforeClass
+ public static void setUpClass() throws FtpException, IOException
+ {
+ FtpProviderTestCase.setUpClass();
+ }
+
+ @AfterClass
+ public static void tearDownClass() throws MalformedURLException, FtpException
+ {
+ FtpProviderTestCase.tearDownClass();
+ }
+
+ private FileObject resolveRoot() throws FileSystemException
+ {
+ return VFS.getManager().resolveFile(FtpProviderTestCase.getConnectionUri());
+ }
+
+ @Test
+ public void testConnectRoot() throws SocketException, IOException
+ {
+ resolveRoot();
+ resolveRoot();
+ }
+
+ @Test
+ public void testUnderlyingConnect() throws SocketException, IOException
+ {
+ final FTPClient client1 = new FTPClient();
+ final FTPClient client2 = new FTPClient();
+ try
+ {
+ final String hostname = "localhost";
+ client1.connect(hostname, FtpProviderTestCase.getSocketPort());
+ client2.connect(hostname, FtpProviderTestCase.getSocketPort());
+ } finally
+ {
+ if (client1 != null)
+ {
+ client1.disconnect();
+ }
+ if (client2 != null)
+ {
+ client2.disconnect();
+ }
+ }
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ftps/test/AbstractFtpsProviderTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ftps/test/AbstractFtpsProviderTestCase.java
new file mode 100644
index 0000000..f82e4aa
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ftps/test/AbstractFtpsProviderTestCase.java
@@ -0,0 +1,225 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ftps.test;
+
+import java.io.File;
+import java.io.IOException;
+import java.net.URL;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.ftps.FtpsFileProvider;
+import org.apache.commons.vfs2.provider.ftps.FtpsFileSystemConfigBuilder;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+import org.apache.commons.vfs2.util.FreeSocketPortUtil;
+import org.apache.ftpserver.FtpServer;
+import org.apache.ftpserver.FtpServerFactory;
+import org.apache.ftpserver.ftplet.FtpException;
+import org.apache.ftpserver.ftplet.UserManager;
+import org.apache.ftpserver.listener.ListenerFactory;
+import org.apache.ftpserver.ssl.SslConfigurationFactory;
+import org.apache.ftpserver.usermanager.PropertiesUserManagerFactory;
+import org.apache.ftpserver.usermanager.impl.BaseUser;
+import org.junit.Assert;
+
+/**
+ * Abstract tests for FTP file systems.
+ */
+abstract class AbstractFtpsProviderTestCase extends AbstractProviderTestConfig implements ProviderTestConfig
+{
+ private static int SocketPort;
+
+ /**
+ * Use %40 for @ in URLs
+ */
+ private static String ConnectionUri;
+
+ 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";
+
+ private static final String SERVER_JKS_RES = "org.apache.ftpsserver/ftpserver.jks";
+
+ static String getConnectionUri()
+ {
+ return ConnectionUri;
+ }
+
+ static int getSocketPort()
+ {
+ return SocketPort;
+ }
+
+ static String getSystemTestUriOverride()
+ {
+ return System.getProperty(TEST_URI);
+ }
+
+ static void init() throws IOException
+ {
+ SocketPort = FreeSocketPortUtil.findFreeLocalPort();
+ // Use %40 for @ in a URL
+ ConnectionUri = "ftps://test:test@localhost:" + SocketPort;
+ }
+
+ /**
+ * Creates and starts an embedded Apache FTP Server (MINA).
+ *
+ * @param implicit FTPS connection mode
+ * @throws FtpException
+ * @throws IOException
+ */
+ static void setUpClass(final boolean implicit) throws FtpException, IOException
+ {
+ if (Server != null)
+ {
+ return;
+ }
+ init();
+ final FtpServerFactory serverFactory = new FtpServerFactory();
+ final PropertiesUserManagerFactory propertiesUserManagerFactory = new PropertiesUserManagerFactory();
+ final URL userPropsResource = ClassLoader.getSystemClassLoader().getResource(USER_PROPS_RES);
+ Assert.assertNotNull(USER_PROPS_RES, userPropsResource);
+ propertiesUserManagerFactory.setUrl(userPropsResource);
+ final UserManager userManager = propertiesUserManagerFactory.createUserManager();
+ final BaseUser user = (BaseUser) userManager.getUserByName("test");
+ // Pickup the home dir value at runtime even though we have it set in the user prop file
+ // The user prop file requires the "homedirectory" to be set
+ user.setHomeDirectory(getTestDirectory());
+ serverFactory.setUserManager(userManager);
+ final ListenerFactory factory = new ListenerFactory();
+ // set the port of the listener
+ factory.setPort(SocketPort);
+
+ // define SSL configuration
+ final URL serverJksResource = ClassLoader.getSystemClassLoader().getResource(SERVER_JKS_RES);
+ Assert.assertNotNull(SERVER_JKS_RES, serverJksResource);
+ final SslConfigurationFactory ssl = new SslConfigurationFactory();
+ final File keyStoreFile = FileUtils.toFile(serverJksResource);
+ Assert.assertTrue(keyStoreFile.toString(), keyStoreFile.exists());
+ ssl.setKeystoreFile(keyStoreFile);
+ ssl.setKeystorePassword("password");
+
+ // set the SSL configuration for the listener
+ factory.setSslConfiguration(ssl.createSslConfiguration());
+ factory.setImplicitSsl(implicit);
+
+ // replace the default listener
+ serverFactory.addListener("default", factory.createListener());
+
+ // start the server
+ Server = serverFactory.createServer();
+ Server.start();
+ }
+
+ /**
+ * Stops the embedded Apache FTP Server (MINA).
+ */
+ static void tearDownClass()
+ {
+ if (Server != null)
+ {
+ Server.stop();
+ Server = null;
+ }
+ }
+
+ 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();
+
+ /**
+ * Returns the base folder for tests. You can override the DEFAULT_URI by using the system property name defined by
+ * TEST_URI.
+ */
+ @Override
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ String uri = getSystemTestUriOverride();
+ if (uri == null)
+ {
+ uri = ConnectionUri;
+ }
+ return manager.resolveFile(uri, getFileSystemOptions());
+ }
+
+ protected FileSystemOptions getFileSystemOptions()
+ {
+ if (fileSystemOptions == null)
+ {
+ fileSystemOptions = new FileSystemOptions();
+ setupOptions(FtpsFileSystemConfigBuilder.getInstance());
+ }
+ return fileSystemOptions;
+ }
+
+ protected void setupOptions(final FtpsFileSystemConfigBuilder builder)
+ {
+ builder.setConnectTimeout(fileSystemOptions, Integer.valueOf(1000));
+ builder.setDataTimeout(fileSystemOptions, Integer.valueOf(2000));
+ }
+
+ /**
+ * Prepares the file system manager.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager) throws Exception
+ {
+ manager.addProvider("ftps", new FtpsFileProvider());
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ftps/test/FtpsProviderExplicitTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ftps/test/FtpsProviderExplicitTestCase.java
new file mode 100644
index 0000000..bb8b373
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ftps/test/FtpsProviderExplicitTestCase.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ftps.test;
+
+import junit.framework.Test;
+
+import org.apache.commons.vfs2.provider.ftps.FtpsDataChannelProtectionLevel;
+import org.apache.commons.vfs2.provider.ftps.FtpsFileSystemConfigBuilder;
+import org.apache.commons.vfs2.provider.ftps.FtpsMode;
+
+/**
+ * Tests for FTPS file systems with explicit FTPS connection.
+ */
+public class FtpsProviderExplicitTestCase extends AbstractFtpsProviderTestCase
+{
+ @Override
+ protected boolean isImplicit()
+ {
+ return false;
+ }
+
+ @Override
+ protected void setupOptions(final FtpsFileSystemConfigBuilder builder)
+ {
+ super.setupOptions(builder);
+ 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/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ftps/test/FtpsProviderImplicitTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ftps/test/FtpsProviderImplicitTestCase.java
new file mode 100644
index 0000000..17d9d07
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ftps/test/FtpsProviderImplicitTestCase.java
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ftps.test;
+
+import junit.framework.Test;
+
+import org.apache.commons.vfs2.provider.ftps.FtpsFileSystemConfigBuilder;
+import org.apache.commons.vfs2.provider.ftps.FtpsMode;
+
+/**
+ * Tests for FTPS file systems with implicit FTPS connection.
+ *
+ * TODO: Fails for concurrent access.
+ * Note, that the implicit mode is not standardized and the protocol may differ between the FTPS servers.
+ * @see <a href="http://en.wikipedia.org/wiki/FTPS#Implicit">Wikipedia: FTPS/Implicit</a>
+ */
+public class FtpsProviderImplicitTestCase extends AbstractFtpsProviderTestCase
+{
+ @Override
+ protected boolean isImplicit()
+ {
+ return true;
+ }
+
+ @Override
+ protected void setupOptions(final FtpsFileSystemConfigBuilder builder)
+ {
+ 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/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ftps/test/MultipleConnectionTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ftps/test/MultipleConnectionTestCase.java
new file mode 100644
index 0000000..96b75b5
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ftps/test/MultipleConnectionTestCase.java
@@ -0,0 +1,87 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ftps.test;
+
+import java.io.IOException;
+import java.net.SocketException;
+
+import org.apache.commons.net.ftp.FTPSClient;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.VFS;
+import org.apache.ftpserver.ftplet.FtpException;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+public class MultipleConnectionTestCase
+{
+
+ @BeforeClass
+ public static void setUpClass() throws FtpException, IOException
+ {
+ AbstractFtpsProviderTestCase.setUpClass(true);
+ }
+
+ @AfterClass
+ public static void tearDownClass()
+ {
+ AbstractFtpsProviderTestCase.tearDownClass();
+ }
+
+ private FTPSClient init(final FTPSClient client)
+ {
+ client.enterLocalPassiveMode();
+ return client;
+ }
+
+ private FileObject resolveRoot() throws FileSystemException
+ {
+ return VFS.getManager().resolveFile(AbstractFtpsProviderTestCase.getConnectionUri(),
+ new FtpsProviderImplicitTestCase().getFileSystemOptions());
+ }
+
+ @Test
+ public void testConnectRoot() throws IOException
+ {
+ resolveRoot();
+ resolveRoot();
+ }
+
+ @Test
+ public void testUnderlyingConnect() throws SocketException, IOException
+ {
+ final FTPSClient client1 = this.init(new FTPSClient(true));
+ final FTPSClient client2 = this.init(new FTPSClient(true));
+ try
+ {
+ final String hostname = "localhost";
+ client1.connect(hostname, AbstractFtpsProviderTestCase.getSocketPort());
+ client2.connect(hostname, AbstractFtpsProviderTestCase.getSocketPort());
+ } finally
+ {
+ if (client1 != null)
+ {
+ client1.disconnect();
+ }
+ if (client2 != null)
+ {
+ client2.disconnect();
+ }
+ }
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/hdfs/test/HdfsFileProviderTest.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/hdfs/test/HdfsFileProviderTest.java
new file mode 100644
index 0000000..160ebb1
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/hdfs/test/HdfsFileProviderTest.java
@@ -0,0 +1,359 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.hdfs.test;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.util.Map;
+
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.vfs2.CacheStrategy;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.cache.DefaultFilesCache;
+import org.apache.commons.vfs2.cache.SoftRefFilesCache;
+import org.apache.commons.vfs2.impl.DefaultFileReplicator;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.impl.FileContentInfoFilenameFactory;
+import org.apache.commons.vfs2.provider.hdfs.HdfsFileAttributes;
+import org.apache.commons.vfs2.provider.hdfs.HdfsFileProvider;
+import org.apache.commons.vfs2.util.Os;
+import org.apache.commons.vfs2.util.RandomAccessMode;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hdfs.DFSConfigKeys;
+import org.apache.hadoop.hdfs.MiniDFSCluster;
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+/**
+ * This test class uses the Hadoop MiniDFSCluster class to create an embedded Hadoop cluster.
+ * <P>
+ * This will only work on systems that Hadoop supports.
+ */
+@SuppressWarnings("resource")
+public class HdfsFileProviderTest
+{
+
+ // Turn off the MiniDFSCluster logging
+ static
+ {
+ System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
+ }
+
+ private static final int PORT = 8620;
+ private static final String HDFS_URI = "hdfs://localhost:" + PORT;
+ private static final String TEST_DIR1 = HDFS_URI + "/test-dir";
+ private static final Path DIR1_PATH = new Path("/test-dir");
+ private static final String TEST_FILE1 = TEST_DIR1 + "/accumulo-test-1.jar";
+ private static final Path FILE1_PATH = new Path(DIR1_PATH, "accumulo-test-1.jar");
+
+ private static DefaultFileSystemManager manager;
+ private static FileSystem hdfs;
+
+ 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
+ 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>
+ * MiniDFSCluster will check the permissions on the data directories, but does not do a
+ * good job of setting them properly. We need to get the users umask and set the
+ * appropriate Hadoop property so that the data directories will be created with
+ * the correct permissions.
+ * <P>
+ * Will do nothing on Windows.
+ */
+ public static void setUmask(Configuration conf2)
+ {
+ if (Os.isFamily(Os.OS_FAMILY_WINDOWS))
+ {
+ return;
+ }
+
+ try
+ {
+ final Process p = Runtime.getRuntime().exec("/bin/sh -c umask");
+ final BufferedReader bri = new BufferedReader(new InputStreamReader(p.getInputStream()));
+ final String line = bri.readLine();
+ p.waitFor();
+ final Short umask = Short.parseShort(line.trim(), 8);
+ // Need to set permission to 777 xor umask
+ // leading zero makes java interpret as base 8
+ final int newPermission = 0777 ^ umask;
+ conf2.set("dfs.datanode.data.dir.perm", String.format("%03o", newPermission));
+ }
+ catch (final Exception e)
+ {
+ throw new RuntimeException("Error getting umask from O/S", e);
+ }
+ }
+
+ @AfterClass
+ public static void tearDown() throws Exception
+ {
+ if (null != hdfs)
+ {
+ hdfs.close();
+ }
+ manager.close();
+ }
+
+ @After
+ public void after() throws Exception
+ {
+ if (null != hdfs)
+ {
+ hdfs.delete(DIR1_PATH, true);
+ }
+ }
+
+ private FileObject createTestFile(final FileSystem hdfs) throws IOException
+ {
+ // Create the directory
+ hdfs.mkdirs(DIR1_PATH);
+ final FileObject dir = manager.resolveFile(TEST_DIR1);
+ Assert.assertNotNull(dir);
+ Assert.assertTrue(dir.exists());
+ Assert.assertTrue(dir.getType().equals(FileType.FOLDER));
+
+ // Create the file in the directory
+ hdfs.create(FILE1_PATH).close();
+ final FileObject f = manager.resolveFile(TEST_FILE1);
+ Assert.assertNotNull(f);
+ Assert.assertTrue(f.exists());
+ Assert.assertTrue(f.getType().equals(FileType.FILE));
+ return f;
+ }
+
+ @Test(expected = UnsupportedOperationException.class)
+ public void testCanRenameTo() throws Exception
+ {
+ final FileObject fo = createTestFile(hdfs);
+ Assert.assertNotNull(fo);
+ fo.canRenameTo(fo);
+ }
+
+ @Test
+ public void testDoListChildren() throws Exception
+ {
+ final FileObject fo = manager.resolveFile(TEST_DIR1);
+ Assert.assertNotNull(fo);
+ Assert.assertFalse(fo.exists());
+
+ // Create the test file
+ final FileObject file = createTestFile(hdfs);
+ Assert.assertTrue(fo.exists());
+ final FileObject dir = file.getParent();
+
+ final FileObject[] children = dir.getChildren();
+ Assert.assertTrue(children.length == 1);
+ Assert.assertTrue(children[0].getName().equals(file.getName()));
+
+ }
+
+ @Test
+ public void testEquals() throws Exception
+ {
+ // Create test file (and check parent was created)
+ final FileObject dir = manager.resolveFile(TEST_DIR1);
+ Assert.assertNotNull(dir);
+ Assert.assertFalse(dir.exists());
+ final FileObject file1 = createTestFile(hdfs);
+ Assert.assertTrue(file1.exists());
+ Assert.assertTrue(dir.exists());
+
+ // Get a handle to the same file and ensure it is equal
+ final FileObject file2 = manager.resolveFile(TEST_FILE1);
+ Assert.assertEquals(file1, file2);
+
+ // Ensure different files on same filesystem are not equal
+ Assert.assertNotEquals(dir, file1);
+ Assert.assertNotEquals(dir, file2);
+ }
+
+ @Test
+ public void testGetAttributes() throws Exception
+ {
+ final FileObject fo = manager.resolveFile(TEST_DIR1);
+ Assert.assertNotNull(fo);
+ Assert.assertFalse(fo.exists());
+
+ // Create the test file
+ final FileObject file = createTestFile(hdfs);
+ Assert.assertTrue(fo.exists());
+ final Map<String, Object> attributes = file.getContent().getAttributes();
+ Assert.assertTrue(attributes.containsKey(HdfsFileAttributes.BLOCK_SIZE.toString()));
+ Assert.assertTrue(attributes.containsKey(HdfsFileAttributes.GROUP.toString()));
+ Assert.assertTrue(attributes.containsKey(HdfsFileAttributes.LAST_ACCESS_TIME.toString()));
+ Assert.assertTrue(attributes.containsKey(HdfsFileAttributes.LENGTH.toString()));
+ Assert.assertTrue(attributes.containsKey(HdfsFileAttributes.MODIFICATION_TIME.toString()));
+ Assert.assertTrue(attributes.containsKey(HdfsFileAttributes.OWNER.toString()));
+ Assert.assertTrue(attributes.containsKey(HdfsFileAttributes.PERMISSIONS.toString()));
+ }
+
+ @Test
+ public void testGetContentSize() throws Exception
+ {
+ final FileObject fo = manager.resolveFile(TEST_DIR1);
+ Assert.assertNotNull(fo);
+ Assert.assertFalse(fo.exists());
+
+ // Create the test file
+ final FileObject file = createTestFile(hdfs);
+ Assert.assertTrue(fo.exists());
+ Assert.assertEquals(0, file.getContent().getSize());
+ }
+
+ @Test
+ public void testGetInputStream() throws Exception
+ {
+ final FileObject fo = manager.resolveFile(TEST_DIR1);
+ Assert.assertNotNull(fo);
+ Assert.assertFalse(fo.exists());
+
+ // Create the test file
+ final FileObject file = createTestFile(hdfs);
+ Assert.assertTrue(fo.exists());
+ file.getContent().getInputStream().close();
+ }
+
+ @Test
+ public void testInit() throws Exception
+ {
+ final FileObject fo = manager.resolveFile(TEST_FILE1);
+ Assert.assertNotNull(fo);
+ Assert.assertFalse(fo.exists());
+ }
+
+ @Test
+ public void testIsHidden() throws Exception
+ {
+ final FileObject fo = manager.resolveFile(TEST_DIR1);
+ Assert.assertNotNull(fo);
+ Assert.assertFalse(fo.exists());
+
+ // Create the test file
+ final FileObject file = createTestFile(hdfs);
+ Assert.assertTrue(fo.exists());
+ Assert.assertFalse(file.isHidden());
+ }
+
+ @Test
+ public void testIsReadable() throws Exception
+ {
+ final FileObject fo = manager.resolveFile(TEST_DIR1);
+ Assert.assertNotNull(fo);
+ Assert.assertFalse(fo.exists());
+
+ // Create the test file
+ final FileObject file = createTestFile(hdfs);
+ Assert.assertTrue(fo.exists());
+ Assert.assertTrue(file.isReadable());
+ }
+
+ @Test
+ public void testIsWritable() throws Exception
+ {
+ final FileObject fo = manager.resolveFile(TEST_DIR1);
+ Assert.assertNotNull(fo);
+ Assert.assertFalse(fo.exists());
+
+ // Create the test file
+ final FileObject file = createTestFile(hdfs);
+ Assert.assertTrue(fo.exists());
+ Assert.assertFalse(file.isWriteable());
+ }
+
+ @Test
+ public void testLastModificationTime() throws Exception
+ {
+ final FileObject fo = manager.resolveFile(TEST_DIR1);
+ Assert.assertNotNull(fo);
+ Assert.assertFalse(fo.exists());
+
+ // Create the test file
+ final FileObject file = createTestFile(hdfs);
+ Assert.assertTrue(fo.exists());
+ Assert.assertFalse(-1 == file.getContent().getLastModifiedTime());
+ }
+
+ @Test(expected = FileSystemException.class)
+ public void testRandomAccessContent() throws Exception
+ {
+ final FileObject fo = manager.resolveFile(TEST_DIR1);
+ Assert.assertNotNull(fo);
+ Assert.assertFalse(fo.exists());
+
+ // Create the test file
+ final FileObject file = createTestFile(hdfs);
+ Assert.assertTrue(fo.exists());
+ file.getContent().getRandomAccessContent(RandomAccessMode.READWRITE).close();
+ }
+
+ @Test
+ public void testRandomAccessContent2() throws Exception
+ {
+ final FileObject fo = manager.resolveFile(TEST_DIR1);
+ Assert.assertNotNull(fo);
+ Assert.assertFalse(fo.exists());
+
+ // Create the test file
+ final FileObject file = createTestFile(hdfs);
+ Assert.assertTrue(fo.exists());
+ file.getContent().getRandomAccessContent(RandomAccessMode.READ).close();
+ }
+
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/hdfs/test/HdfsFileProviderTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/hdfs/test/HdfsFileProviderTestCase.java
new file mode 100644
index 0000000..3b92e53
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/hdfs/test/HdfsFileProviderTestCase.java
@@ -0,0 +1,173 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.hdfs.test;
+
+import java.io.File;
+import java.io.IOException;
+
+import junit.framework.Test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.hdfs.HdfsFileProvider;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.fs.FileSystem;
+import org.apache.hadoop.fs.Path;
+import org.apache.hadoop.hdfs.DFSConfigKeys;
+import org.apache.hadoop.hdfs.MiniDFSCluster;
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+
+/**
+ * This test class uses the Hadoop MiniDFSCluster class to create an embedded Hadoop cluster.
+ * <P>
+ * This will only work on systems that Hadoop supports.
+ */
+public class HdfsFileProviderTestCase extends AbstractProviderTestConfig implements ProviderTestConfig
+{
+ public static class HdfsProviderTestSuite extends ProviderTestSuite
+ {
+
+ // Turn off the MiniDFSCluster logging
+ static
+ {
+ System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
+ }
+
+ public HdfsProviderTestSuite(final ProviderTestConfig providerConfig, final boolean addEmptyDir) throws Exception
+ {
+ super(providerConfig, addEmptyDir);
+ }
+
+ @SuppressWarnings("deprecation")
+ private void copyTestResources(final File directory, final Path parent) throws Exception
+ {
+ for (final File file : directory.listFiles())
+ {
+ if (file.isFile())
+ {
+ final Path src = new Path(file.getAbsolutePath());
+ final Path dst = new Path(parent, file.getName());
+ hdfs.copyFromLocalFile(src, dst);
+ }
+ else if (file.isDirectory())
+ {
+ final Path dir = new Path(parent, file.getName());
+ if (hdfs.mkdirs(dir))
+ {
+ copyTestResources(file, dir);
+ }
+ else
+ {
+ fail("Unable to make directory: " + dir);
+ }
+ }
+ }
+
+ }
+
+ @SuppressWarnings("deprecation")
+ @Override
+ protected void setUp() throws Exception
+ {
+ Logger.getRootLogger().setLevel(Level.OFF);
+
+ // Put the MiniDFSCluster directory in the target directory
+ File data = new File("target/test/hdfstestcasedata").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
+
+ HdfsFileProviderTest.setUmask(conf);
+
+ try
+ {
+ cluster = new MiniDFSCluster(PORT, conf, 1, true, true, true, null, null, null, null);
+ cluster.waitActive();
+ }
+ catch (final IOException e)
+ {
+ throw new RuntimeException("Error setting up mini cluster", e);
+ }
+ hdfs = cluster.getFileSystem();
+
+ // Copy the test directory into HDFS
+ final Path base = new Path("/test-data");
+ assertTrue("Unable to create base directory", hdfs.mkdirs(base));
+ final File testDir = AbstractVfsTestCase.getTestDirectoryFile();
+ copyTestResources(testDir, base);
+
+ super.setUp();
+ }
+
+ @Override
+ protected void tearDown() throws Exception
+ {
+ super.tearDown();
+ if (null != hdfs)
+ {
+ hdfs.close();
+ }
+ }
+ }
+ private static final int PORT = 8720;
+ private static final String HDFS_URI = "hdfs://localhost:" + PORT;
+ private static FileSystem hdfs;
+ private static Configuration conf;
+
+ private static MiniDFSCluster cluster;
+
+ /**
+ * Creates the test suite for the zip file system.
+ */
+ public static Test suite() throws Exception
+ {
+ return new HdfsProviderTestSuite(new HdfsFileProviderTestCase(), false);
+ }
+
+ /**
+ * Returns the base folder for read tests.
+ */
+ @Override
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ final String uri = HDFS_URI + "/test-data";
+ return manager.resolveFile(uri);
+ }
+
+ /**
+ * Prepares the file system manager.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager) throws Exception
+ {
+ manager.addProvider("hdfs", new HdfsFileProvider());
+ }
+
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/http/test/GetContentInfoFunctionalTest.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/http/test/GetContentInfoFunctionalTest.java
new file mode 100644
index 0000000..7e86952
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/http/test/GetContentInfoFunctionalTest.java
@@ -0,0 +1,51 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.http.test;
+
+import org.apache.commons.vfs2.FileContent;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.VFS;
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * Tests VFS-427 NPE on HttpFileObject.getContent().getContentInfo()
+ *
+ * @since 2.1
+ */
+public class GetContentInfoFunctionalTest
+{
+
+ /**
+ * Tests VFS-427 NPE on HttpFileObject.getContent().getContentInfo().
+ *
+ * @throws FileSystemException
+ * thrown when the getContentInfo API fails.
+ */
+ @Test
+ public void testGoogle() throws FileSystemException
+ {
+ final FileSystemManager fsManager = VFS.getManager();
+ final FileObject fo = fsManager.resolveFile("http://www.google.com/images/logos/ps_logo2.png");
+ final FileContent content = fo.getContent();
+ Assert.assertNotNull(content);
+ // Used to NPE before fix:
+ content.getContentInfo();
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/http/test/HttpFilesCacheTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/http/test/HttpFilesCacheTestCase.java
new file mode 100644
index 0000000..2378639
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/http/test/HttpFilesCacheTestCase.java
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.http.test;
+
+import junit.framework.TestCase;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.VFS;
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * Tests https://issues.apache.org/jira/browse/VFS-426
+ *
+ * @version $Id$
+ * @since 2.1
+ */
+public class HttpFilesCacheTestCase extends TestCase
+{
+
+ /**
+ * Tests https://issues.apache.org/jira/browse/VFS-426
+ */
+ @Test
+ public void testQueryStringUrls() throws FileSystemException
+ {
+ final String noQueryStringUrl = "http://commons.apache.org/vfs";
+ final String queryStringUrl = "http://commons.apache.org/vfs?query=string";
+ final String queryStringUrl2 = "http://commons.apache.org/vfs?query=string&more=stuff";
+
+ final FileSystemManager fileSystemManager = VFS.getManager();
+
+ final FileObject noQueryFile = fileSystemManager.resolveFile(noQueryStringUrl);
+ Assert.assertEquals(noQueryStringUrl, noQueryFile.getURL().toExternalForm());
+
+ final FileObject queryFile = fileSystemManager.resolveFile(queryStringUrl);
+ Assert.assertEquals(queryStringUrl, queryFile.getURL().toExternalForm()); // failed for VFS-426
+
+ final FileObject queryFile2 = fileSystemManager.resolveFile(queryStringUrl2);
+ Assert.assertEquals(queryStringUrl2, queryFile2.getURL().toExternalForm()); // failed for VFS-426
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/http/test/HttpProviderTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/http/test/HttpProviderTestCase.java
new file mode 100644
index 0000000..6f6af3b
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/http/test/HttpProviderTestCase.java
@@ -0,0 +1,234 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.http.test;
+
+import java.io.File;
+import java.io.IOException;
+
+import junit.framework.Test;
+
+import org.apache.commons.vfs2.FileNotFolderException;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.VFS;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.http.HttpFileProvider;
+import org.apache.commons.vfs2.provider.http.HttpFileSystemConfigBuilder;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+import org.apache.commons.vfs2.util.FreeSocketPortUtil;
+import org.apache.commons.vfs2.util.NHttpServer;
+import org.junit.Assert;
+
+/**
+ * Test cases for the HTTP provider.
+ *
+ */
+public class HttpProviderTestCase extends AbstractProviderTestConfig
+{
+ private static NHttpServer Server;
+
+ private static int SocketPort;
+
+ private static final String TEST_URI = "test.http.uri";
+
+ /**
+ * Use %40 for @ in URLs
+ */
+ private static String ConnectionUri;
+
+ private static String getSystemTestUriOverride()
+ {
+ return System.getProperty(TEST_URI);
+ }
+
+ /**
+ * Creates and starts an embedded Apache HTTP Server (HttpComponents).
+ *
+ * @throws Exception
+ */
+ private static void setUpClass() throws Exception
+ {
+ Server = new NHttpServer();
+ if (!Server.run(SocketPort, new File(getTestDirectory()), 5000))
+ {
+ throw new IllegalStateException("The embedded HTTP server has not completed startup, increase wait time");
+ }
+ }
+
+ /**
+ * Creates a new test suite.
+ *
+ * @return a new test suite.
+ * @throws Exception
+ * Thrown when the suite cannot be constructed.
+ */
+ public static Test suite() throws Exception
+ {
+ return new ProviderTestSuite(new HttpProviderTestCase())
+ {
+ /**
+ * Adds base tests - excludes the nested test cases.
+ */
+ @Override
+ protected void addBaseTests() throws Exception
+ {
+ super.addBaseTests();
+ addTests(HttpProviderTestCase.class);
+ }
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ if (getSystemTestUriOverride() == null)
+ {
+ setUpClass();
+ }
+ super.setUp();
+ }
+
+ @Override
+ protected void tearDown() throws Exception
+ {
+ tearDownClass();
+ super.tearDown();
+ }
+ };
+ }
+
+ /**
+ * Stops the embedded Apache HTTP Server.
+ *
+ * @throws IOException
+ */
+ private static void tearDownClass() throws IOException
+ {
+ if (Server != null)
+ {
+ Server.stop();
+ }
+ }
+
+ /**
+ * Builds a new test case.
+ *
+ * @throws IOException
+ * Thrown if a free local socket port cannot be found.
+ */
+ public HttpProviderTestCase() throws IOException
+ {
+ SocketPort = FreeSocketPortUtil.findFreeLocalPort();
+ // Use %40 for @ in a URL
+ ConnectionUri = "http://localhost:" + SocketPort;
+ }
+
+ private void checkReadTestsFolder(final FileObject file) throws FileSystemException
+ {
+ Assert.assertNotNull(file.getChildren());
+ Assert.assertTrue(file.getChildren().length > 0);
+ }
+
+ /**
+ * Returns the base folder for tests.
+ */
+ @Override
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ String uri = getSystemTestUriOverride();
+ if (uri == null)
+ {
+ uri = ConnectionUri;
+ }
+ return manager.resolveFile(uri);
+ }
+
+ /**
+ * Prepares the file system manager.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager) throws Exception
+ {
+ manager.addProvider("http", new HttpFileProvider());
+ }
+
+ private void testResloveFolderSlash(final String uri, final boolean followRedirect) throws FileSystemException
+ {
+ VFS.getManager().getFilesCache().close();
+ final FileSystemOptions opts = new FileSystemOptions();
+ HttpFileSystemConfigBuilder.getInstance().setFollowRedirect(opts, followRedirect);
+ final FileObject file = VFS.getManager().resolveFile(uri, opts);
+ try
+ {
+ checkReadTestsFolder(file);
+ } catch (final FileNotFolderException e)
+ {
+ // Expected: VFS HTTP does not support listing children yet.
+ }
+ }
+
+ public void testResloveFolderSlashNoRedirectOff() throws FileSystemException
+ {
+ testResloveFolderSlash(ConnectionUri + "/read-tests", false);
+ }
+
+ public void testResloveFolderSlashNoRedirectOn() throws FileSystemException
+ {
+ testResloveFolderSlash(ConnectionUri + "/read-tests", true);
+ }
+
+ public void testResloveFolderSlashYesRedirectOff() throws FileSystemException
+ {
+ testResloveFolderSlash(ConnectionUri + "/read-tests/", false);
+ }
+
+ public void testResloveFolderSlashYesRedirectOn() throws FileSystemException
+ {
+ testResloveFolderSlash(ConnectionUri + "/read-tests/", true);
+ }
+
+ // Test no longer passing 2016/04/28
+ public void ignoreTestHttp405() throws FileSystemException
+ {
+ final FileObject f = VFS.getManager().resolveFile("http://www.w3schools.com/webservices/tempconvert.asmx?action=WSDL");
+ assert f.getContent().getSize() > 0;
+ }
+
+ /** Ensure VFS-453 options are present. */
+ public void testHttpTimeoutConfig() throws FileSystemException
+ {
+ final FileSystemOptions opts = new FileSystemOptions();
+ final HttpFileSystemConfigBuilder builder = HttpFileSystemConfigBuilder.getInstance();
+
+ // ensure defaults are 0
+ assertEquals(0, builder.getConnectionTimeout(opts));
+ assertEquals(0, builder.getSoTimeout(opts));
+ assertEquals("Jakarta-Commons-VFS", builder.getUserAgent(opts));
+
+ builder.setConnectionTimeout(opts, 60000);
+ builder.setSoTimeout(opts, 60000);
+ builder.setUserAgent(opts, "foo/bar");
+
+ // ensure changes are visible
+ assertEquals(60000, builder.getConnectionTimeout(opts));
+ assertEquals(60000, builder.getSoTimeout(opts));
+ assertEquals("foo/bar", builder.getUserAgent(opts));
+
+ // TODO: should also check the created HTTPClient
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/https/test/GetContentInfoFunctionalTest.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/https/test/GetContentInfoFunctionalTest.java
new file mode 100644
index 0000000..5ef3fe8
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/https/test/GetContentInfoFunctionalTest.java
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.https.test;
+
+import java.net.MalformedURLException;
+import java.net.URL;
+
+import org.apache.commons.vfs2.FileContent;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.VFS;
+import org.apache.commons.vfs2.provider.http.HttpFileSystemConfigBuilder;
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * Tests VFS-427 NPE on HttpFileObject.getContent().getContentInfo()
+ *
+ * @since 2.1
+ */
+public class GetContentInfoFunctionalTest
+{
+
+ /**
+ * Tests VFS-427 NPE on HttpFileObject.getContent().getContentInfo().
+ *
+ * @throws FileSystemException
+ * thrown when the getContentInfo API fails.
+ * @throws MalformedURLException
+ * thrown when the System environment contains an invalid URL for an HTTPS proxy.
+ */
+ @Test
+ public void testGoogle() throws FileSystemException, MalformedURLException
+ {
+ String httpsProxyHost = null;
+ int httpsProxyPort = -1;
+ final String httpsProxy = System.getenv("https_proxy");
+ if (httpsProxy != null) {
+ final URL url = new URL(httpsProxy);
+ httpsProxyHost = url.getHost();
+ httpsProxyPort = url.getPort();
+ }
+ final FileSystemOptions opts;
+ if (httpsProxyHost != null) {
+ opts = new FileSystemOptions();
+ final HttpFileSystemConfigBuilder builder = HttpFileSystemConfigBuilder.getInstance();
+ builder.setProxyHost(opts, httpsProxyHost);
+ if (httpsProxyPort >= 0) {
+ builder.setProxyPort(opts, httpsProxyPort);
+ }
+ } else {
+ opts = null;
+ }
+
+ final FileSystemManager fsManager = VFS.getManager();
+ final FileObject fo = fsManager.resolveFile("https://www.google.com/images/logos/ps_logo2.png", opts);
+ final FileContent content = fo.getContent();
+ Assert.assertNotNull(content);
+ // Used to NPE before fix:
+ content.getContentInfo();
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/jar/test/JarAttributesTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/jar/test/JarAttributesTestCase.java
new file mode 100644
index 0000000..e6efd14
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/jar/test/JarAttributesTestCase.java
@@ -0,0 +1,65 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.jar.test;
+
+import java.util.Map;
+
+import junit.framework.TestCase;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.VFS;
+import org.junit.Assert;
+import org.junit.Test;
+
+/**
+ * Tests JAR attributes.
+ *
+ * @version $Id$
+ */
+public class JarAttributesTestCase extends TestCase
+{
+ private void printAttributes(final Map<String, Object> attributes)
+ {
+ for (final Map.Entry<String, Object> e : attributes.entrySet())
+ {
+ System.out.println("Key: " + e.getKey() + ", Value: " + e.getValue());
+ }
+ }
+
+ @Test
+ public void testAttributes() throws Exception
+ {
+ final FileObject file = JarProviderTestCase.getTestJar(VFS.getManager(), "test.jar");
+
+ final Map<String, Object> attributes = file.getContent().getAttributes();
+ Assert.assertEquals("1.0", attributes.get("Manifest-Version"));
+ // Debugging:
+ // this.printAttributes(attributes);
+ }
+
+ @Test
+ public void testNestedAttributes() throws Exception
+ {
+ final FileObject nested = JarProviderTestCase.getTestJar(VFS.getManager(), "nested.jar");
+ final FileObject file = nested.resolveFile("test.jar");
+
+ final Map<String, Object> attributes = file.getContent().getAttributes();
+ Assert.assertEquals("1.0", attributes.get("Manifest-Version"));
+ // Debugging:
+ // this.printAttributes(attributes);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/jar/test/JarProviderTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/jar/test/JarProviderTestCase.java
new file mode 100644
index 0000000..7ba42da
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/jar/test/JarProviderTestCase.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.jar.test;
+
+import java.io.File;
+
+import junit.framework.Test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.jar.JarFileProvider;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+
+/**
+ * Tests for the Jar file system.
+ */
+public class JarProviderTestCase extends AbstractProviderTestConfig implements ProviderTestConfig
+{
+ static FileObject getTestJar(final FileSystemManager manager, final String name) throws Exception
+ {
+ final File jarFile = AbstractVfsTestCase.getTestResource(name);
+ final String uri = "jar:file:" + jarFile.getAbsolutePath() + "!/";
+ return manager.resolveFile(uri);
+ }
+
+ /**
+ * Creates the test suite for the jar file system.
+ */
+ public static Test suite() throws Exception
+ {
+ return new ProviderTestSuite(new JarProviderTestCase(), true);
+ }
+
+ /**
+ * Returns the base folder for tests.
+ */
+ @Override
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ return JarProviderTestCase.getTestJar(manager, "test.jar");
+ }
+
+ /**
+ * Prepares the file system manager.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager) throws Exception
+ {
+ manager.addProvider("jar", new JarFileProvider());
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/jar/test/NestedJarTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/jar/test/NestedJarTestCase.java
new file mode 100644
index 0000000..6b7a50d
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/jar/test/NestedJarTestCase.java
@@ -0,0 +1,73 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.jar.test;
+
+import java.io.File;
+
+import junit.framework.Test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.jar.JarFileProvider;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+
+/**
+ * Tests for the Zip file system.
+ */
+public class NestedJarTestCase
+ extends AbstractProviderTestConfig
+ implements ProviderTestConfig
+{
+ /**
+ * Creates the test suite for nested jar files.
+ */
+ public static Test suite() throws Exception
+ {
+ return new ProviderTestSuite(new NestedJarTestCase(), true);
+ }
+
+ /**
+ * 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
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ // Locate the Jar file
+ final File outerFile = AbstractVfsTestCase.getTestResource("nested.jar");
+ final String uri = "jar:file:" + outerFile.getAbsolutePath() + "!/test.jar";
+ final FileObject jarFile = manager.resolveFile(uri);
+
+ // Now build the nested file system
+ final FileObject nestedFS = manager.createFileSystem(jarFile);
+ return nestedFS.resolveFile("/");
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/local/test/ConversionTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/local/test/ConversionTestCase.java
new file mode 100644
index 0000000..780e786
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/local/test/ConversionTestCase.java
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.local.test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.IOException;
+import java.net.URISyntaxException;
+import java.net.URL;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.VFS;
+import org.junit.Ignore;
+import org.junit.Test;
+
+/**
+ * Tests conversion from VFS to File.
+ * <p>
+ * VFS-443 Need an easy way to convert from a FileObject to a File.
+ */
+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();
+ assertEquals(file.getAbsoluteFile(), new File(file.toURI().getPath()));
+ assertEquals(file.getAbsoluteFile(), new File(new URL(fileURL).toURI().getPath()));
+ try
+ {
+ new FileOutputStream(file).close();
+ assertTrue(file.exists());
+
+ final FileSystemManager manager = VFS.getManager();
+ final FileObject fo = manager.resolveFile(fileURL);
+ assertTrue(fo.exists());
+ assertEquals(file.getAbsoluteFile(), new File(new URL(fo.getURL().toExternalForm()).toURI().getPath()));
+ }
+ finally
+ {
+ file.delete();
+ }
+ }
+
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/local/test/FileNameTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/local/test/FileNameTests.java
new file mode 100644
index 0000000..33d84a3
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/local/test/FileNameTests.java
@@ -0,0 +1,45 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.local.test;
+
+import java.io.File;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.test.AbstractProviderTestCase;
+
+/**
+ * Additional naming tests for local file system.
+ */
+public class FileNameTests
+ extends AbstractProviderTestCase
+{
+ /**
+ * Tests resolution of an absolute file name.
+ */
+ public void testAbsoluteFileName() throws Exception
+ {
+ // Locate file by absolute file name
+ final String fileName = new File("testdir").getAbsolutePath();
+ final FileObject absFile = getManager().resolveFile(fileName);
+
+ // Locate file by URI
+ final String uri = "file://" + fileName.replace(File.separatorChar, '/');
+ final FileObject uriFile = getManager().resolveFile(uri);
+
+ assertSame("file object", absFile, uriFile);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/local/test/LocalProviderTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/local/test/LocalProviderTestCase.java
new file mode 100644
index 0000000..06d4602
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/local/test/LocalProviderTestCase.java
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.local.test;
+
+import java.io.File;
+
+import junit.framework.Test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.PermissionsTests;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+import org.apache.commons.vfs2.util.Os;
+
+/**
+ * Tests for the local file system.
+ */
+public class LocalProviderTestCase
+ extends AbstractProviderTestConfig
+ implements ProviderTestConfig
+{
+ /**
+ * Creates the test suite for the local file system.
+ */
+ public static Test suite() throws Exception
+ {
+ final ProviderTestSuite testSuite = new ProviderTestSuite(new LocalProviderTestCase());
+
+ testSuite.addTests(FileNameTests.class);
+ // VFS-325
+ testSuite.addTests(UrlTests.class);
+ testSuite.addTests(PermissionsTests.class);
+
+ if (Os.isFamily(Os.OS_FAMILY_WINDOWS))
+ {
+ testSuite.addTests(WindowsFileNameTests.class);
+ }
+
+ return testSuite;
+ }
+
+ /**
+ * Returns the base folder for tests.
+ */
+ @Override
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ final File testDir = AbstractVfsTestCase.getTestDirectoryFile();
+ return manager.toFileObject(testDir);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/local/test/UrlTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/local/test/UrlTests.java
new file mode 100644
index 0000000..713a1dd
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/local/test/UrlTests.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.local.test;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.Selectors;
+import org.apache.commons.vfs2.VFS;
+import org.apache.commons.vfs2.provider.UriParser;
+import org.apache.commons.vfs2.test.AbstractProviderTestCase;
+
+/**
+ * Additional URL tests for local file system.
+ *
+ * @version $Revision$
+ */
+public class UrlTests
+ extends AbstractProviderTestCase
+{
+ /**
+ * Tests FindFiles with a filename that has a hash sign in it.
+ */
+ public void testHashFindFiles() throws Exception
+ {
+ final FileSystemManager fsManager = VFS.getManager();
+
+ final FileObject[] foList = getBaseFolder().findFiles(Selectors.SELECT_FILES);
+
+ boolean hashFileFound = false;
+ for (final FileObject fo : foList)
+ {
+ if (fo.getURL().toString().contains("test-hash"))
+ {
+ hashFileFound = true;
+
+ assertEquals(fo.toString(), UriParser.decode(fo.getURL().toString()));
+ }
+ }
+
+ if (!hashFileFound)
+ {
+ fail("Test hash file containing 'test-hash' not found");
+ }
+ }
+
+ /**
+ * Tests resolution of an absolute file name.
+ */
+ public void testHashURL() throws Exception
+ {
+ final FileObject file = getReadFolder().resolveFile("test-hash-#test.txt");
+
+ assertEquals(file.toString(), UriParser.decode(file.getURL().toString()));
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/local/test/WindowsFileNameTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/local/test/WindowsFileNameTests.java
new file mode 100644
index 0000000..ea858c9
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/local/test/WindowsFileNameTests.java
@@ -0,0 +1,110 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.local.test;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.provider.local.WindowsFileName;
+import org.apache.commons.vfs2.test.AbstractProviderTestCase;
+
+/**
+ * Additional naming tests for local file system.
+ * <p>
+ * Only executed on Windows O/S.
+ */
+public class WindowsFileNameTests
+ extends AbstractProviderTestCase
+{
+ public void testWindowsRoots() throws Exception
+ {
+ // valid URI forms of the filesystem root
+ String[] tests = new String[] { "file:///C:/", "file://C:/", "file:/C:/", "file:C:/" };
+
+ for(String name : tests)
+ {
+ FileName fn = getManager().resolveFile(name).getName();
+
+ // the following tests work for Windows file names only
+ assertSame(WindowsFileName.class, fn.getClass());
+
+ // all should result in the same FileName
+ assertEquals("file:///C:/", fn.toString());
+ assertEquals("/", fn.getPath());
+ assertEquals("/", fn.getPathDecoded());
+ assertEquals("file:///C:/", fn.getRootURI());
+ assertEquals("file:///C:/", fn.getFriendlyURI());
+
+ assertEquals("file:///C:/", fn.getRoot().toString());
+
+ assertEquals("", fn.getExtension());
+ assertEquals("", fn.getBaseName());
+ }
+ }
+
+ public void testWindowsWrongRoots() throws Exception
+ {
+ String[] tests = new String[] { "file:///C:", "file://C:", "file:/C:", "file:C:" };
+
+ for(String name : tests)
+ {
+ try
+ {
+ FileName fn = getManager().resolveFile(name).getName();
+ fail("should not accept root " + name);
+ }
+ catch (FileSystemException ex)
+ {
+ assertEquals("vfs.provider/invalid-absolute-uri.error", ex.getCode());
+ assertTrue(ex.toString().indexOf(name) >= 0);
+ }
+ }
+ }
+
+ public void testWindowsFilenameUNCStartError() throws Exception
+ {
+ try
+ {
+ final String FILE = "file://///";
+ FileObject fo = getManager().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());
+ }
+ }
+
+ public void testWindowsFilenameParserError() throws Exception
+ {
+ // check VFS-338 with 2+4 slashes we want a dedicated error
+ try
+ {
+ final String FILE = "file://////";
+ FileObject fo = getManager().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/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ram/test/CustomRamProviderTest.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ram/test/CustomRamProviderTest.java
new file mode 100644
index 0000000..bc0b7e0
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ram/test/CustomRamProviderTest.java
@@ -0,0 +1,272 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ram.test;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.io.Closeable;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
+
+import org.apache.commons.vfs2.FileContent;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.ram.RamFileProvider;
+import org.apache.commons.vfs2.provider.ram.RamFileSystemConfigBuilder;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * Custom tests
+ *
+ * @version $Id$
+ */
+public class CustomRamProviderTest
+{
+ private static final byte[] NON_EMPTY_FILE_CONTENT = new byte[]{ 1, 2, 3 };
+
+ private final List<Closeable> closeables = new ArrayList<Closeable>();
+
+ FileSystemOptions defaultRamFso = new FileSystemOptions();
+
+ DefaultFileSystemManager manager;
+
+ FileSystemOptions smallSizedFso = new FileSystemOptions();
+
+ FileSystemOptions zeroSizedFso = new FileSystemOptions();
+
+ /**
+ * Closes the given {@link Closeable} during the tearDown phase.
+ */
+ private <C extends Closeable> C closeOnTearDown(final C closeable)
+ {
+ this.closeables.add(closeable);
+ return closeable;
+ }
+
+ private InputStream createEmptyFile() throws FileSystemException, IOException
+ {
+ final FileObject root = manager.resolveFile("ram://file");
+ root.createFile();
+ return this.closeOnTearDown(root.getContent().getInputStream());
+ }
+
+ private InputStream createNonEmptyFile() throws FileSystemException, IOException
+ {
+ final FileObject root = manager.resolveFile("ram://file");
+ root.createFile();
+
+ final FileContent content = root.getContent();
+ final OutputStream output = this.closeOnTearDown(content.getOutputStream());
+ output.write(1);
+ output.write(2);
+ output.write(3);
+ output.flush();
+ output.close();
+
+ return this.closeOnTearDown(content.getInputStream());
+ }
+
+ @Before
+ public void setUp() throws Exception
+ {
+ manager = new DefaultFileSystemManager();
+ manager.addProvider("ram", new RamFileProvider());
+ manager.init();
+
+ // File Systems Options
+ RamFileSystemConfigBuilder.getInstance().setMaxSize(zeroSizedFso, 0L);
+ RamFileSystemConfigBuilder.getInstance().setMaxSize(smallSizedFso, 10L);
+ }
+
+ @After
+ public void tearDown() throws Exception
+ {
+ for (final Closeable closeable : this.closeables)
+ {
+ try
+ {
+ closeable.close();
+ } catch (final Exception e)
+ {
+ // ignore
+ }
+ }
+ manager.close();
+ }
+
+ @Test
+ public void testReadEmptyFileByteByByte() throws FileSystemException, IOException
+ {
+ final InputStream input = this.createEmptyFile();
+ assertEquals("Empty file didnt return EOF -1", -1, input.read());
+ }
+
+ @Test
+ public void testReadEmptyFileIntoBuffer() throws FileSystemException, IOException
+ {
+ final InputStream input = this.createEmptyFile();
+
+ final byte[] buffer = new byte[100];
+ assertEquals("Empty file didnt return when filling buffer", -1, input.read(buffer));
+ assertArrayEquals("Buffer was written too", new byte[100], buffer);
+ }
+
+ @Test
+ public void testReadEmptyFileIntoBufferWithOffsetAndLength() throws FileSystemException, IOException
+ {
+ final InputStream input = this.createEmptyFile();
+ final byte[] buffer = new byte[100];
+ assertEquals("Empty file didnt return when filling buffer", -1, input.read(buffer, 10, 90));
+ assertArrayEquals("Buffer was written too", new byte[100], buffer);
+ }
+
+ @Test
+ public void testReadNonEmptyFileByteByByte() throws FileSystemException, IOException
+ {
+ final InputStream input = this.createNonEmptyFile();
+
+ assertEquals("Read 1st byte failed", 1, input.read());
+ assertEquals("Rread 2st byte failed", 2, input.read());
+ assertEquals("Read 3st byte failed", 3, input.read());
+ assertEquals("File should be empty", -1, input.read());
+ }
+
+ @Test
+ public void testReadNonEmptyFileIntoBuffer() throws FileSystemException, IOException
+ {
+ final InputStream input = this.createNonEmptyFile();
+
+ final byte[] buffer = new byte[100];
+ assertEquals("Filling buffer failed when file is not empty", NON_EMPTY_FILE_CONTENT.length, input.read(buffer));
+
+ final byte[] expectedBuffer = new byte[100];
+ System.arraycopy(NON_EMPTY_FILE_CONTENT, 0, expectedBuffer, 0, NON_EMPTY_FILE_CONTENT.length);
+ assertArrayEquals("Buffer not filled", expectedBuffer, buffer);
+
+ Arrays.fill(buffer, (byte) 0);
+ Arrays.fill(expectedBuffer, (byte) 0);
+
+ assertEquals("File should be empty after filling buffer", -1, input.read(buffer));
+ assertArrayEquals("Buffer was written when empty", expectedBuffer, buffer);
+ }
+
+ @Test
+ public void testReadNonEmptyFileIntoBufferWithOffsetAndLength() throws FileSystemException, IOException
+ {
+ final InputStream input = this.createNonEmptyFile();
+
+ final byte[] buffer = new byte[100];
+ final int offset = 10;
+ assertEquals("Filling buffer failed when file is not empty", NON_EMPTY_FILE_CONTENT.length,
+ input.read(buffer, offset, 100 - offset));
+
+ final byte[] expectedBuffer = new byte[100];
+ System.arraycopy(NON_EMPTY_FILE_CONTENT, 0, expectedBuffer, offset, NON_EMPTY_FILE_CONTENT.length);
+ assertArrayEquals("Buffer not filled", expectedBuffer, buffer);
+
+ Arrays.fill(buffer, (byte) 0);
+ Arrays.fill(expectedBuffer, (byte) 0);
+ assertEquals("File should be empty after filling buffer", -1, input.read(buffer, 10, 90));
+ assertArrayEquals("Buffer was written when empty", expectedBuffer, buffer);
+ }
+
+ /**
+ *
+ * Checks root folder exists
+ *
+ * @throws FileSystemException
+ */
+ @Test
+ public void testRootFolderExists() throws FileSystemException
+ {
+ final FileObject root = manager.resolveFile("ram:///", defaultRamFso);
+ assertTrue(root.getType().hasChildren());
+
+ try
+ {
+ root.delete();
+ fail();
+ } catch (final FileSystemException e)
+ {
+ // Expected
+ }
+
+ }
+
+ @Test
+ public void testFSOptions() throws Exception
+ {
+ // Default FS
+ final FileObject fo1 = manager.resolveFile("ram:/");
+ final FileObject fo2 = manager.resolveFile("ram:/");
+ assertTrue("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);
+ assertTrue("Both files should exist in the same FileSystem instance.", fo3.getFileSystem() == fo4.getFileSystem());
+ assertTrue("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);
+ }
+
+ @Test
+ public void testSmallFS() throws Exception
+ {
+ // Small FS
+ final FileObject fo3 = manager.resolveFile("ram:/fo3", smallSizedFso);
+ fo3.createFile();
+ try
+ {
+ final OutputStream os = fo3.getContent().getOutputStream();
+ os.write(new byte[10]);
+ os.close();
+ } catch (final FileSystemException e)
+ {
+ fail("Test should be able to save such a small file");
+ }
+
+ try
+ {
+ final OutputStream os = fo3.getContent().getOutputStream();
+ os.write(new byte[11]);
+ os.close();
+ fail("It shouldn't save such a big file");
+ } catch (final FileSystemException e)
+ {
+ // Expected
+ }
+
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ram/test/RamProviderTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ram/test/RamProviderTestCase.java
new file mode 100644
index 0000000..f57d4f7
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/ram/test/RamProviderTestCase.java
@@ -0,0 +1,97 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.ram.test;
+
+
+import junit.framework.Test;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.local.DefaultLocalFileProvider;
+import org.apache.commons.vfs2.provider.ram.RamFileProvider;
+import org.apache.commons.vfs2.provider.ram.RamFileSystem;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+
+/**
+ * Tests for the RAM file system.
+ */
+public class RamProviderTestCase extends AbstractProviderTestConfig implements
+ ProviderTestConfig
+{
+ private boolean inited = false;
+
+ /** logger */
+ private static Log log = LogFactory.getLog(RamProviderTestCase.class);
+
+ /**
+ * Creates the test suite for the ram file system.
+ */
+ public static Test suite() throws Exception
+ {
+ 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;
+ }
+ }
+
+ /**
+ * Returns the base folder for tests.
+ */
+ @Override
+ public FileObject getBaseTestFolder(final FileSystemManager manager)
+ throws Exception
+ {
+ if (!inited)
+ {
+ // Import the test tree
+ final FileObject fo = manager.resolveFile("ram:/");
+ final RamFileSystem fs = (RamFileSystem) fo.getFileSystem();
+ fs.importTree(getTestDirectoryFile());
+ fo.close();
+
+ inited=true;
+ }
+
+ final String uri = "ram:/";
+ return manager.resolveFile(uri);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/res/test/ResourceProviderTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/res/test/ResourceProviderTestCase.java
new file mode 100644
index 0000000..027542e
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/res/test/ResourceProviderTestCase.java
@@ -0,0 +1,64 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.commons.vfs2.provider.res.test;
+
+import junit.framework.Test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.jar.JarFileProvider;
+import org.apache.commons.vfs2.provider.res.ResourceFileProvider;
+import org.apache.commons.vfs2.provider.url.UrlFileProvider;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+
+/**
+ * Test cases for the resource provider.
+ */
+public class ResourceProviderTestCase extends AbstractProviderTestConfig
+{
+ public static Test suite() throws Exception
+ {
+ return new ProviderTestSuite(new ResourceProviderTestCase());
+ }
+
+ /**
+ * 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("file", new UrlFileProvider());
+ manager.addProvider("jar", new JarFileProvider());
+ }
+
+ /**
+ * Returns the base folder for tests.
+ */
+ @Override
+ public FileObject getBaseTestFolder(final FileSystemManager manager)
+ throws Exception
+ {
+ final String baseDir = AbstractVfsTestCase.getResourceTestDirectory();
+ return manager.resolveFile("res:" + baseDir);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/sftp/test/SftpProviderTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/sftp/test/SftpProviderTestCase.java
new file mode 100644
index 0000000..bf6480d
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/sftp/test/SftpProviderTestCase.java
@@ -0,0 +1,785 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.sftp.test;
+
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.io.PrintStream;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.net.URI;
+import java.security.PublicKey;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.TreeMap;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import junit.extensions.TestSetup;
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.sftp.SftpFileProvider;
+import org.apache.commons.vfs2.provider.sftp.SftpFileSystem;
+import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;
+import org.apache.commons.vfs2.provider.sftp.SftpStreamProxy;
+import org.apache.commons.vfs2.provider.sftp.TrustEveryoneUserInfo;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.PermissionsTests;
+import org.apache.commons.vfs2.test.ProviderReadTests;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+import org.apache.commons.vfs2.util.FreeSocketPortUtil;
+import org.apache.ftpserver.ftplet.FtpException;
+import org.apache.sshd.SshServer;
+import org.apache.sshd.common.NamedFactory;
+import org.apache.sshd.common.Session;
+import org.apache.sshd.common.SshException;
+import org.apache.sshd.common.session.AbstractSession;
+import org.apache.sshd.common.util.Buffer;
+import org.apache.sshd.common.util.SecurityUtils;
+import org.apache.sshd.server.Command;
+import org.apache.sshd.server.Environment;
+import org.apache.sshd.server.ExitCallback;
+import org.apache.sshd.server.FileSystemFactory;
+import org.apache.sshd.server.FileSystemView;
+import org.apache.sshd.server.ForwardingFilter;
+import org.apache.sshd.server.PasswordAuthenticator;
+import org.apache.sshd.server.PublickeyAuthenticator;
+import org.apache.sshd.server.SshFile;
+import org.apache.sshd.server.auth.UserAuthNone;
+import org.apache.sshd.server.command.ScpCommandFactory;
+import org.apache.sshd.server.filesystem.NativeSshFile;
+import org.apache.sshd.server.keyprovider.PEMGeneratorHostKeyProvider;
+import org.apache.sshd.server.keyprovider.SimpleGeneratorHostKeyProvider;
+import org.apache.sshd.server.session.ServerSession;
+import org.apache.sshd.server.sftp.SftpSubsystem;
+
+import com.jcraft.jsch.SftpATTRS;
+import com.jcraft.jsch.TestIdentityRepositoryFactory;
+
+/**
+ * Tests cases for the SFTP provider.
+ * <p>
+ * Starts and stops an embedded Apache SSHd (MINA) server.
+ * </p>
+ */
+public class SftpProviderTestCase extends AbstractProviderTestConfig
+{
+ /**
+ * The underlying filesystem
+ */
+ private SftpFileSystem filesystem;
+
+ /**
+ * 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);
+ }
+ }
+
+ /**
+ * 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";
+
+ private static String ConnectionUri;
+
+ private static SshServer Server;
+
+ private static final String TEST_URI = "test.sftp.uri";
+
+ /** True if we are testing the SFTP stream proxy */
+ private final boolean streamProxyMode;
+
+ private 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() throws FtpException, IOException, InterruptedException
+ {
+ SocketPort = FreeSocketPortUtil.findFreeLocalPort();
+ // Use %40 for @ in a URL
+ ConnectionUri = String.format("sftp://%s@localhost:%d", DEFAULT_USER, SocketPort);
+
+ 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(SocketPort);
+ 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();
+
+ 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<NamedFactory<Command>>(1);
+ list.add(new NamedFactory<Command>()
+ {
+
+ @Override
+ public String getName()
+ {
+ return "sftp";
+ }
+
+ @Override
+ public Command create()
+ {
+ return new MySftpSubsystem();
+ }
+ });
+ Server.setSubsystemFactories(list);
+ Server.setPasswordAuthenticator(new PasswordAuthenticator()
+ {
+ @Override
+ public boolean authenticate(final String username, final String password, final ServerSession session)
+ {
+ return username != null && username.equals(password);
+ }
+ });
+ Server.setPublickeyAuthenticator(new PublickeyAuthenticator()
+ {
+ @Override
+ public boolean authenticate(final String username, final PublicKey key, final ServerSession session)
+ {
+ // File f = new File("/Users/" + username + "/.ssh/authorized_keys");
+ return true;
+ }
+ });
+ Server.setForwardingFilter(new ForwardingFilter()
+ {
+ @Override
+ public boolean canConnect(final InetSocketAddress address, final ServerSession session)
+ {
+ return true;
+ }
+
+ @Override
+ public boolean canForwardAgent(final ServerSession session)
+ {
+ return true;
+ }
+
+ @Override
+ public boolean canForwardX11(final ServerSession session)
+ {
+ return true;
+ }
+
+ @Override
+ public boolean canListen(final InetSocketAddress address, final ServerSession session)
+ {
+ return true;
+ }
+ });
+ // Allows the execution of commands
+ Server.setCommandFactory(new ScpCommandFactory(new TestCommandFactory()));
+ // HACK Start
+ // How do we really do simple user to directory matching?
+ Server.setFileSystemFactory(new TestFileSystemFactory());
+ // HACK End
+ Server.start();
+ // 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 private class BaseProviderTestSuite extends ProviderTestSuite {
+
+ public BaseProviderTestSuite(final ProviderTestConfig providerConfig) throws Exception
+ {
+ super(providerConfig);
+ }
+
+ @Override
+ protected void tearDown() throws Exception
+ {
+ // Close all active sessions
+ // Note that it should be done by super.tearDown()
+ // while closing
+ for (final AbstractSession session : Server.getActiveSessions()) {
+ session.close(true);
+ }
+ super.tearDown();
+ }
+
+ }
+
+ /**
+ * Creates the test suite for the ftp file system.
+ */
+ public static Test suite() throws Exception
+ {
+ // The test suite to be returned
+ final TestSuite suite = new TestSuite();
+
+ // --- Standard VFS test suite
+ final SftpProviderTestCase standardTestCase = new SftpProviderTestCase(false);
+ final ProviderTestSuite sftpSuite = new BaseProviderTestSuite(standardTestCase);
+
+ // VFS-405: set/get permissions
+ sftpSuite.addTests(PermissionsTests.class);
+
+ suite.addTest(sftpSuite);
+
+
+ // --- 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
+ // hence if the reading test succeeds/fails the other will also succeed/fail)
+ final SftpProviderTestCase streamProxyTestCase = new SftpProviderTestCase(true);
+ final ProviderTestSuite sftpStreamSuite = new BaseProviderTestSuite(streamProxyTestCase)
+ {
+ @Override
+ protected void addBaseTests() throws Exception
+ {
+ // Just tries to read
+ addTests(ProviderReadTests.class);
+ }
+ };
+ suite.addTest(sftpStreamSuite);
+
+
+ // Decorate the test suite to set up the Sftp server
+ final TestSetup setup = new TestSetup(suite)
+ {
+ @Override
+ protected void setUp() throws Exception
+ {
+ if (getSystemTestUriOverride() == null)
+ {
+ setUpClass();
+ }
+ super.setUp();
+ }
+
+ @Override
+ protected void tearDown() throws Exception
+ {
+ // Close SFTP server if needed
+ tearDownClass();
+ super.tearDown();
+ }
+ };
+
+
+ return setup;
+ }
+
+ /**
+ * Stops the embedded Apache SSHd Server (MINA).
+ *
+ * @throws InterruptedException
+ */
+ private static void tearDownClass() throws InterruptedException
+ {
+ if (Server != null)
+ {
+ Server.stop();
+ }
+ }
+
+ public SftpProviderTestCase(final boolean streamProxyMode) throws IOException
+ {
+ this.streamProxyMode = streamProxyMode;
+ }
+
+ /**
+ * 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());
+
+ if (streamProxyMode)
+ {
+ final FileSystemOptions proxyOptions = (FileSystemOptions) fileSystemOptions.clone();
+
+ final URI parsedURI = new URI(uri);
+ final String userInfo = parsedURI.getUserInfo();
+ final String[] userFields = userInfo.split(":", 2);
+
+ builder.setProxyType(fileSystemOptions, SftpFileSystemConfigBuilder.PROXY_STREAM);
+ builder.setProxyUser(fileSystemOptions, userFields[0]);
+ if (userFields.length > 1)
+ {
+ builder.setProxyPassword(fileSystemOptions, userFields[1]);
+ }
+ builder.setProxyHost(fileSystemOptions, parsedURI.getHost());
+ builder.setProxyPort(fileSystemOptions, parsedURI.getPort());
+ builder.setProxyCommand(fileSystemOptions, SftpStreamProxy.NETCAT_COMMAND);
+ builder.setProxyOptions(fileSystemOptions, proxyOptions);
+ builder.setProxyPassword(fileSystemOptions, parsedURI.getAuthority());
+
+ // Set up the new URI
+ uri = String.format("sftp://%s@localhost:%d", userInfo, parsedURI.getPort());
+ }
+
+ 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>
+ * <li><code>id -u</code> (permissions test)</li>
+ * <li><code>id -G</code> (permission tests)</li>
+ * <li><code>nc -q 0 localhost port</code> (Stream proxy tests)</li>
+ * </p>
+ */
+ private static class TestCommandFactory extends ScpCommandFactory
+ {
+
+ public static final Pattern NETCAT_COMMAND = Pattern.compile("nc -q 0 localhost (\\d+)");
+
+ @Override
+ public Command createCommand(final String command)
+ {
+ return new Command()
+ {
+ public ExitCallback callback = null;
+ public OutputStream out = null;
+ public OutputStream err = null;
+ public InputStream in = null;
+
+ @Override
+ public void setInputStream(final InputStream in)
+ {
+ this.in = in;
+ }
+
+ @Override
+ public void setOutputStream(final OutputStream out)
+ {
+ this.out = out;
+ }
+
+ @Override
+ public void setErrorStream(final OutputStream err)
+ {
+ this.err = err;
+ }
+
+ @Override
+ public void setExitCallback(final ExitCallback callback)
+ {
+ this.callback = callback;
+
+ }
+
+ @Override
+ public void start(final Environment env) throws IOException
+ {
+ int code = 0;
+ if (command.equals("id -G") || command.equals("id -u"))
+ {
+ new PrintStream(out).println(0);
+ } else if (NETCAT_COMMAND.matcher(command).matches())
+ {
+ final Matcher matcher = NETCAT_COMMAND.matcher(command);
+ matcher.matches();
+ final int port = Integer.parseInt(matcher.group(1));
+
+ final Socket socket = new Socket((String) null, port);
+
+ if (out != null)
+ {
+ connect("from nc", socket.getInputStream(), out, null);
+ }
+
+ if (in != null)
+ {
+ connect("to nc", in, socket.getOutputStream(), callback);
+ }
+
+ return;
+
+ } else
+ {
+ if (err != null)
+ {
+ new PrintStream(err).format("Unknown command %s%n", command);
+ }
+ code = -1;
+ }
+
+ if (out != null)
+ {
+ out.flush();
+ }
+ if (err != null)
+ {
+ err.flush();
+ }
+ callback.onExit(code);
+ }
+
+ @Override
+ public void destroy()
+ {
+ }
+ };
+ }
+ }
+
+ /**
+ * Creates a pipe thread that connects an input to an output
+ * @param name The name of the thread (for debugging purposes)
+ * @param in The input stream
+ * @param out The output stream
+ * @param callback An object whose method {@linkplain ExitCallback#onExit(int)} will be
+ * called when the pipe is broken. The integer argument is 0 if everything
+ * went well.
+ */
+ private static void connect(final String name, final InputStream in, final OutputStream out, final ExitCallback callback)
+ {
+ final Thread thread = new Thread(new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ int code = 0;
+ try
+ {
+ final byte buffer[] = new byte[1024];
+ int len;
+ while ((len = in.read(buffer, 0, buffer.length)) != -1)
+ {
+ out.write(buffer, 0, len);
+ out.flush();
+ }
+ }
+ catch (final SshException ex)
+ {
+ // Nothing to do, this occurs when the connection
+ // is closed on the remote side
+ }
+ catch (final IOException ex)
+ {
+ if (!ex.getMessage().equals("Pipe closed"))
+ {
+ code = -1;
+ }
+ }
+ if (callback != null)
+ {
+ callback.onExit(code);
+ }
+ }
+ }, name);
+ thread.setDaemon(true);
+ thread.start();
+ }
+
+
+ private static class SftpAttrs
+ {
+ int flags = 0;
+ private int uid;
+ long size = 0;
+ private int gid;
+ private int atime;
+ private int permissions;
+ private int mtime;
+ private String[] extended;
+
+ private SftpAttrs(final Buffer buf)
+ {
+ int flags = 0;
+ 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();
+ }
+
+ }
+ }
+
+ private static class MySftpSubsystem extends SftpSubsystem
+ {
+ TreeMap<String, Integer> permissions = new TreeMap<String, Integer>();
+ private int _version;
+
+ @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();
+
+ 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;
+ }
+
+ 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;
+ }
+
+ case SSH_FXP_INIT:
+ {
+ // Just grab the version here
+ this._version = id;
+ break;
+ }
+ }
+
+ buffer.rpos(rpos);
+ super.process(buffer);
+
+ }
+
+ @Override
+ protected void writeAttrs(final Buffer buffer, final SshFile file, final int flags) throws IOException
+ {
+ if (!file.doesExist()) {
+ throw new FileNotFoundException(file.getAbsolutePath());
+ }
+
+
+ int p = 0;
+
+ 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;
+ }
+ }
+
+ 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;
+ }
+
+
+ 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);
+ }
+ }
+ }
+
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/tar/test/LargeTarTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/tar/test/LargeTarTestCase.java
new file mode 100644
index 0000000..3f21084
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/tar/test/LargeTarTestCase.java
@@ -0,0 +1,216 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.tar.test;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.io.OutputStream;
+import java.io.PipedInputStream;
+import java.io.PipedOutputStream;
+import java.util.Arrays;
+import java.util.List;
+
+import org.apache.commons.compress.archivers.ArchiveStreamFactory;
+import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
+import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
+import org.apache.commons.compress.compressors.CompressorStreamFactory;
+import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
+import org.apache.commons.compress.utils.IOUtils;
+import org.apache.commons.vfs2.CacheStrategy;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.cache.SoftRefFilesCache;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.local.DefaultLocalFileProvider;
+import org.apache.commons.vfs2.provider.tar.TarFileProvider;
+import org.junit.Before;
+import org.junit.Test;
+
+//@SuppressWarnings("nls")
+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);
+
+ assertTrue("Expected file not found: " + largeFileName + ".txt",
+ f.getName().getBaseName().equals(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;
+ }
+
+ //@SuppressWarnings("unused")
+ protected void createLargeFile(final String path, final String name) throws Exception {
+ final long _1K = 1024;
+ final long _1M = 1024 * _1K;
+// long _256M = 256 * _1M;
+// long _512M = 512 * _1M;
+ final long _1G = 1024 * _1M;
+
+ // File size of 3 GB
+ final long fileSize = 3 * _1G;
+
+ final File tarGzFile = new File(path + name + ".tar.gz");
+
+ if(!tarGzFile.exists()) {
+ System.out.println("This test is a bit slow. It needs to write 3GB of data as a compressed file (approx. 3MB) to your hard drive");
+
+ final PipedOutputStream outTarFileStream = new PipedOutputStream();
+ final PipedInputStream inTarFileStream = new PipedInputStream(outTarFileStream);
+
+ final Thread source = new Thread(){
+
+ @Override
+ public void run() {
+ final byte ba_1k[] = new byte[(int) _1K];
+ for(int i=0; i < ba_1k.length; i++){
+ ba_1k[i]='a';
+ }
+ try {
+ final TarArchiveOutputStream outTarStream =
+ (TarArchiveOutputStream)new ArchiveStreamFactory()
+ .createArchiveOutputStream(ArchiveStreamFactory.TAR, outTarFileStream);
+ // Create archive contents
+ final TarArchiveEntry tarArchiveEntry = new TarArchiveEntry(name + ".txt");
+ tarArchiveEntry.setSize(fileSize);
+
+ outTarStream.putArchiveEntry(tarArchiveEntry);
+ for(long i = 0; i < fileSize; i+= ba_1k.length) {
+ outTarStream.write(ba_1k);
+ }
+ outTarStream.closeArchiveEntry();
+ outTarStream.close();
+ outTarFileStream.close();
+ } catch (final Exception e) {
+ e.printStackTrace();
+ }
+ }
+
+ };
+ source.start();
+
+ // Create compressed archive
+ final OutputStream outGzipFileStream = new FileOutputStream(path + name + ".tar.gz");
+
+ final GzipCompressorOutputStream outGzipStream = (GzipCompressorOutputStream)new CompressorStreamFactory()
+ .createCompressorOutputStream(CompressorStreamFactory.GZIP, outGzipFileStream);
+
+ IOUtils.copy(inTarFileStream, outGzipStream);
+ inTarFileStream.close();
+
+ outGzipStream.close();
+ outGzipFileStream.close();
+
+ }
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/tar/test/NestedTarTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/tar/test/NestedTarTestCase.java
new file mode 100644
index 0000000..cc18179
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/tar/test/NestedTarTestCase.java
@@ -0,0 +1,80 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.tar.test;
+
+import junit.framework.Test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemConfigBuilder;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.auth.StaticUserAuthenticator;
+import org.apache.commons.vfs2.impl.DefaultFileSystemConfigBuilder;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.tar.TarFileProvider;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+
+/**
+ * Tests for the Tar file system, using a tar file nested inside another tar file.
+ */
+public class NestedTarTestCase
+ extends AbstractProviderTestConfig
+ implements ProviderTestConfig
+{
+ /**
+ * Creates the test suite for nested tar files.
+ */
+ public static Test suite() throws Exception
+ {
+ return new ProviderTestSuite(new NestedTarTestCase(), true);
+ }
+
+ /**
+ * 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
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ // We test with non-empty FS options to make sure they are propagated
+ final FileSystemOptions opts = new FileSystemOptions();
+ DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, new StaticUserAuthenticator("domain", null, null));
+
+ // Locate the base Tar file
+ final String tarFilePath = AbstractVfsTestCase.getTestResource("nested.tar").getAbsolutePath();
+
+ // Now build the nested file system
+ final String uri = "tar:file:" + tarFilePath + "!/test.tar";
+ final FileObject tarFile = manager.resolveFile(uri, opts);
+ final FileObject nestedFS = manager.createFileSystem(tarFile);
+ return nestedFS.resolveFile("/");
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/tar/test/NestedTbz2TestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/tar/test/NestedTbz2TestCase.java
new file mode 100644
index 0000000..f8f8235
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/tar/test/NestedTbz2TestCase.java
@@ -0,0 +1,72 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.tar.test;
+
+import junit.framework.Test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.tar.TarFileProvider;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+
+/**
+ * Tests for the Tar file system, using a tar file nested inside another tar file.
+ */
+public class NestedTbz2TestCase
+ extends AbstractProviderTestConfig
+ implements ProviderTestConfig
+{
+ /**
+ * Creates the test suite for nested tar files.
+ */
+ public static Test suite() throws Exception
+ {
+ return new ProviderTestSuite(new NestedTbz2TestCase(), true);
+ }
+
+ /**
+ * 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
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ // Locate the base Tar file
+ final String tarFilePath = AbstractVfsTestCase.getTestResource("nested.tbz2").getAbsolutePath();
+ final String uri = "tbz2:file:" + tarFilePath + "!/test.tbz2";
+ final FileObject tarFile = manager.resolveFile(uri);
+
+ // Now build the nested file system
+ final FileObject nestedFS = manager.createFileSystem(tarFile);
+ return nestedFS.resolveFile("/");
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/tar/test/NestedTgzTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/tar/test/NestedTgzTestCase.java
new file mode 100644
index 0000000..69746b6
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/tar/test/NestedTgzTestCase.java
@@ -0,0 +1,72 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.tar.test;
+
+import junit.framework.Test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.tar.TarFileProvider;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+
+/**
+ * Tests for the Tar file system, using a tar file nested inside another tar file.
+ */
+public class NestedTgzTestCase
+ extends AbstractProviderTestConfig
+ implements ProviderTestConfig
+{
+ /**
+ * Creates the test suite for nested tar files.
+ */
+ public static Test suite() throws Exception
+ {
+ return new ProviderTestSuite(new NestedTgzTestCase(), true);
+ }
+
+ /**
+ * 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
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ // Locate the base Tar file
+ final String tarFilePath = AbstractVfsTestCase.getTestResource("nested.tgz").getAbsolutePath();
+ final String uri = "tgz:file:" + tarFilePath + "!/test.tgz";
+ final FileObject tarFile = manager.resolveFile(uri);
+
+ // Now build the nested file system
+ final FileObject nestedFS = manager.createFileSystem(tarFile);
+ return nestedFS.resolveFile("/");
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/tar/test/TarProviderTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/tar/test/TarProviderTestCase.java
new file mode 100644
index 0000000..2aa466e
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/tar/test/TarProviderTestCase.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.tar.test;
+
+import java.io.File;
+
+import junit.framework.Test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.tar.TarFileProvider;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+
+/**
+ * Tests for the Tar file system.
+ */
+public class TarProviderTestCase
+ extends AbstractProviderTestConfig
+ implements ProviderTestConfig
+{
+ /**
+ * Creates the test suite for the tar file system.
+ */
+ public static Test suite() throws Exception
+ {
+ return new ProviderTestSuite(new TarProviderTestCase(), true);
+ }
+
+ /**
+ * 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
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ final File tarFile = AbstractVfsTestCase.getTestResource("test.tar");
+ final String uri = "tar:file:" + tarFile.getAbsolutePath() + "!/";
+ return manager.resolveFile(uri);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/tar/test/Tbz2ProviderTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/tar/test/Tbz2ProviderTestCase.java
new file mode 100644
index 0000000..5104518
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/tar/test/Tbz2ProviderTestCase.java
@@ -0,0 +1,67 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.tar.test;
+
+import java.io.File;
+
+import junit.framework.Test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.tar.TarFileProvider;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+
+/**
+ * Tests for the Tar file system.
+ */
+public class Tbz2ProviderTestCase
+ extends AbstractProviderTestConfig
+ implements ProviderTestConfig
+{
+ /**
+ * Creates the test suite for the tar file system.
+ */
+ public static Test suite() throws Exception
+ {
+ return new ProviderTestSuite(new Tbz2ProviderTestCase(), true);
+ }
+
+ /**
+ * 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
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ final File tarFile = AbstractVfsTestCase.getTestResource("test.tbz2");
+ final String uri = "tbz2:file:" + tarFile.getAbsolutePath() + "!/";
+ return manager.resolveFile(uri);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/tar/test/TgzProviderTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/tar/test/TgzProviderTestCase.java
new file mode 100644
index 0000000..dc8db6b
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/tar/test/TgzProviderTestCase.java
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.tar.test;
+
+import java.io.File;
+
+import junit.framework.Test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.tar.TarFileProvider;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+
+/**
+ * Tests for the Tar file system.
+ */
+public class TgzProviderTestCase
+ extends AbstractProviderTestConfig
+ implements ProviderTestConfig
+{
+ /**
+ * Creates the test suite for the tar file system.
+ */
+ public static Test suite() throws Exception
+ {
+ return new ProviderTestSuite(new TgzProviderTestCase(), true);
+ }
+
+ /**
+ * 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
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ final File tarFile = AbstractVfsTestCase.getTestResource("test.tgz");
+ final String uri = "tgz:file:" + tarFile.getAbsolutePath() + "!/";
+ return manager.resolveFile(uri);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/temp/test/TemporaryProviderTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/temp/test/TemporaryProviderTestCase.java
new file mode 100644
index 0000000..43009fe
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/temp/test/TemporaryProviderTestCase.java
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.temp.test;
+
+import java.io.File;
+
+import junit.framework.Test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.temp.TemporaryFileProvider;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+
+/**
+ * Test cases for the tmp: file provider.
+ */
+public class TemporaryProviderTestCase
+ extends AbstractProviderTestConfig
+ implements ProviderTestConfig
+{
+ /**
+ * Creates the test suite for the tmp file system.
+ */
+ public static Test suite() throws Exception
+ {
+ return new ProviderTestSuite(new TemporaryProviderTestCase());
+ }
+
+ /**
+ * Prepares the file system manager.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager)
+ throws Exception
+ {
+ final File baseDir = AbstractVfsTestCase.getTestDirectoryFile();
+ manager.addProvider("tmp", new TemporaryFileProvider(baseDir));
+ }
+
+ /**
+ * Returns the base folder for tests.
+ */
+ @Override
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ return manager.resolveFile("tmp:/");
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/test/FileObjectSortTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/test/FileObjectSortTestCase.java
new file mode 100644
index 0000000..93eb682
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/test/FileObjectSortTestCase.java
@@ -0,0 +1,137 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.test;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.VFS;
+import org.junit.Assert;
+import org.junit.BeforeClass;
+import org.junit.Test;
+
+/**
+ * Tests FileObject sorting.
+ *
+ * $Id$
+ */
+public class FileObjectSortTestCase {
+
+ /**
+ * The size of arrays to sort.
+ */
+ private static final int SIZE = 100;
+
+ // Consider @Immutable
+ private static FileSystem VfsFileSystem;
+
+ // Consider @Immutable
+ private static FileObject[] SortedArray;
+
+ // Consider @Immutable
+ private static FileObject[] UnSortedArray;
+
+ private static FileObject resolveFile(final FileSystem fs, final int i) throws FileSystemException {
+ return fs.resolveFile(String.format("%010d", i));
+ }
+
+ @BeforeClass
+ public static void setUpClass() throws FileSystemException {
+ VfsFileSystem = VFS.getManager().createVirtualFileSystem("vfs://").getFileSystem();
+ SortedArray = new FileObject[SIZE];
+ for (int i = 0; i < SIZE; i++) {
+ SortedArray[i] = FileObjectSortTestCase.resolveFile(VfsFileSystem, i);
+ }
+ UnSortedArray = new FileObject[SIZE];
+ for (int i = 0; i < SIZE; i++) {
+ UnSortedArray[i] = FileObjectSortTestCase.resolveFile(VfsFileSystem, SIZE - i - 1);
+ }
+ }
+
+ /**
+ * Tests that sorting ignores case.
+ *
+ * @throws FileSystemException
+ */
+ @Test
+ public void testSortArrayIgnoreCase() throws FileSystemException {
+ final FileObject file1 = VfsFileSystem.resolveFile("A1");
+ final FileObject file2 = VfsFileSystem.resolveFile("a2");
+ final FileObject file3 = VfsFileSystem.resolveFile("A3");
+ final FileObject[] actualArray = { file3, file1, file2, file1, file2 };
+ final FileObject[] expectedArray = { file1, file1, file2, file2, file3 };
+ Arrays.sort(actualArray);
+ Assert.assertArrayEquals(expectedArray, actualArray);
+ }
+
+ /**
+ * Tests sorting an array
+ *
+ * @throws FileSystemException
+ */
+ @Test
+ public void testSortArrayMoveAll() throws FileSystemException {
+ final FileObject[] actualArray = UnSortedArray.clone();
+ Assert.assertFalse(Arrays.equals(UnSortedArray, SortedArray));
+ Arrays.sort(actualArray);
+ Assert.assertArrayEquals(SortedArray, actualArray);
+ }
+
+ /**
+ * Tests that sorting an array already in oder does not mess it up.
+ *
+ * @throws FileSystemException
+ */
+ @Test
+ public void testSortArrayMoveNone() throws FileSystemException {
+ final FileObject[] actualArray = SortedArray.clone();
+ Arrays.sort(actualArray);
+ Assert.assertArrayEquals(SortedArray, actualArray);
+ }
+
+ /**
+ * Tests sorting a list
+ *
+ * @throws FileSystemException
+ */
+ @Test
+ public void testSortListMoveAll() throws FileSystemException {
+ final List<FileObject> actualList = Arrays.asList(UnSortedArray);
+ final List<FileObject> expectedSortedList = Arrays.asList(SortedArray);
+ Assert.assertFalse(actualList.equals(expectedSortedList));
+ Collections.sort(actualList);
+ Assert.assertTrue(actualList.equals(expectedSortedList));
+ }
+
+ /**
+ * Tests that sorting a list already in oder does not mess it up.
+ *
+ * @throws FileSystemException
+ */
+ @Test
+ public void testSortListMoveNone() throws FileSystemException {
+ final List<FileObject> actualList = Arrays.asList(SortedArray);
+ final List<FileObject> expectedSortedList = Arrays.asList(SortedArray);
+ Collections.sort(actualList);
+ Assert.assertTrue(actualList.equals(expectedSortedList));
+ }
+
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/test/GenericFileNameTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/test/GenericFileNameTestCase.java
new file mode 100644
index 0000000..925922e
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/test/GenericFileNameTestCase.java
@@ -0,0 +1,144 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.provider.GenericFileName;
+import org.apache.commons.vfs2.provider.URLFileNameParser;
+
+/**
+ * Some GenericFileName test cases.
+ */
+public class GenericFileNameTestCase
+ extends AbstractVfsTestCase
+{
+ /**
+ * Tests parsing a URI into its parts.
+ */
+ public void testParseUri() throws Exception
+ {
+ final URLFileNameParser urlParser = new URLFileNameParser(21);
+ // Simple name
+ GenericFileName name = (GenericFileName) urlParser.parseUri(null, null, "ftp://hostname/file");
+ assertEquals("ftp", name.getScheme());
+ assertNull(name.getUserName());
+ assertNull(name.getPassword());
+ assertEquals("hostname", name.getHostName());
+ assertEquals(21, name.getPort());
+ assertEquals(name.getDefaultPort(), name.getPort());
+ assertEquals("/file", name.getPath());
+ assertEquals("ftp://hostname/", name.getRootURI());
+ assertEquals("ftp://hostname/file", name.getURI());
+
+ // Name with port
+ name = (GenericFileName) urlParser.parseUri(null, null, "ftp://hostname:9090/file");
+ assertEquals("ftp", name.getScheme());
+ assertNull(name.getUserName());
+ assertNull(name.getPassword());
+ assertEquals("hostname", name.getHostName());
+ assertEquals(9090, name.getPort());
+ assertEquals("/file", name.getPath());
+ assertEquals("ftp://hostname:9090/", name.getRootURI());
+ assertEquals("ftp://hostname:9090/file", name.getURI());
+
+ // Name with no path
+ name = (GenericFileName) urlParser.parseUri(null, null, "ftp://hostname");
+ assertEquals("ftp", name.getScheme());
+ assertNull(name.getUserName());
+ assertNull(name.getPassword());
+ assertEquals("hostname", name.getHostName());
+ assertEquals(21, name.getPort());
+ assertEquals("/", name.getPath());
+ assertEquals("ftp://hostname/", name.getRootURI());
+ assertEquals("ftp://hostname/", name.getURI());
+
+ // Name with username
+ name = (GenericFileName) urlParser.parseUri(null, null, "ftp://user@hostname/file");
+ assertEquals("ftp", name.getScheme());
+ assertEquals("user", name.getUserName());
+ assertNull(name.getPassword());
+ assertEquals("hostname", name.getHostName());
+ assertEquals(21, name.getPort());
+ assertEquals("/file", name.getPath());
+ assertEquals("ftp://user@hostname/", name.getRootURI());
+ assertEquals("ftp://user@hostname/file", name.getURI());
+
+ // Name with username and password
+ name = (GenericFileName) urlParser.parseUri(null, null, "ftp://user:password@hostname/file");
+ assertEquals("ftp", name.getScheme());
+ assertEquals("user", name.getUserName());
+ assertEquals("password", name.getPassword());
+ assertEquals("hostname", name.getHostName());
+ assertEquals(21, name.getPort());
+ assertEquals("/file", name.getPath());
+ assertEquals("ftp://user:password@hostname/", name.getRootURI());
+ assertEquals("ftp://user:password@hostname/file", name.getURI());
+
+ // Encoded username and password
+ name = (GenericFileName) urlParser.parseUri(null, null, "ftp://%75ser%3A:%40@hostname");
+ assertEquals("ftp", name.getScheme());
+ assertEquals("user:", name.getUserName());
+ assertEquals("@", name.getPassword());
+ assertEquals("hostname", name.getHostName());
+ assertEquals(21, name.getPort());
+ assertEquals("/", name.getPath());
+ assertEquals("ftp://user%3a:%40@hostname/", name.getRootURI());
+ assertEquals("ftp://user%3a:%40@hostname/", name.getURI());
+ }
+
+ /**
+ * Tests error handling in URI parser.
+ */
+ 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/trunk/core/src/test/java/org/apache/commons/vfs2/provider/test/JunctionProviderConfig.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/test/JunctionProviderConfig.java
new file mode 100644
index 0000000..6aa9f7b
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/test/JunctionProviderConfig.java
@@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.test;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FilesCache;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+
+/**
+ * A provider config that wraps another provider, to run the tests via
+ * junctions.
+ */
+public class JunctionProviderConfig
+ implements ProviderTestConfig
+{
+ private final ProviderTestConfig config;
+
+ public JunctionProviderConfig(final ProviderTestConfig config)
+ {
+ this.config = config;
+ }
+
+ /**
+ * Returns a DefaultFileSystemManager instance (or subclass instance).
+ */
+ @Override
+ public DefaultFileSystemManager getDefaultFileSystemManager() {
+ return config.getDefaultFileSystemManager();
+ }
+
+ @Override
+ public FilesCache getFilesCache()
+ {
+ return config.getFilesCache();
+ }
+
+ /**
+ * Prepares the file system manager.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager) throws Exception
+ {
+ config.prepare(manager);
+ }
+
+ /**
+ * 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);
+ }
+
+ @Override
+ public boolean isFileSystemRootAccessible()
+ {
+ return true;
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/test/JunctionTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/test/JunctionTests.java
new file mode 100644
index 0000000..d09a38a
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/test/JunctionTests.java
@@ -0,0 +1,106 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.test;
+
+import java.io.File;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.test.AbstractProviderTestCase;
+
+/**
+ * Additional junction test cases.
+ */
+public class JunctionTests
+ extends AbstractProviderTestCase
+{
+ private FileObject getBaseDir() throws FileSystemException
+ {
+ final File file = AbstractVfsTestCase.getTestDirectoryFile();
+ assertTrue(file.exists());
+ return getManager().toFileObject(file);
+ }
+
+ /**
+ * Checks nested junctions are not supported.
+ */
+ 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.
+ */
+ public void testAncestors() throws Exception
+ {
+ final FileSystem fs = getManager().createVirtualFileSystem("vfs://").getFileSystem();
+ final FileObject baseDir = getBaseDir();
+
+ // Make sure the file at the junction point and its ancestors do not exist
+ FileObject file = fs.resolveFile("/a/b");
+ assertFalse(file.exists());
+ file = file.getParent();
+ assertFalse(file.exists());
+ file = file.getParent();
+ assertFalse(file.exists());
+
+ // Add the junction
+ fs.addJunction("/a/b", baseDir);
+
+ // Make sure the file at the junction point and its ancestors exist
+ file = fs.resolveFile("/a/b");
+ assertTrue("Does not exist", file.exists());
+ file = file.getParent();
+ assertTrue("Does not exist", file.exists());
+ file = file.getParent();
+ assertTrue("Does not exist", file.exists());
+ }
+
+ // Check that file @ junction point exists only when backing file exists
+ // Add 2 junctions with common parent
+ // Compare real and virtual files
+ // Events
+ // Remove junctions
+
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/test/VirtualProviderTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/test/VirtualProviderTestCase.java
new file mode 100644
index 0000000..0d15c51
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/test/VirtualProviderTestCase.java
@@ -0,0 +1,52 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.test;
+
+import java.io.File;
+
+import junit.framework.Test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+
+/**
+ * Test cases for the virtual file system provider.
+ */
+public class VirtualProviderTestCase
+ extends AbstractProviderTestConfig
+{
+ public static Test suite() throws Exception
+ {
+ final ProviderTestSuite testSuite = new ProviderTestSuite(new VirtualProviderTestCase());
+ testSuite.addTests(JunctionTests.class);
+ return testSuite;
+ }
+
+ /**
+ * Returns the base folder for tests.
+ */
+ @Override
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ final File baseDir = AbstractVfsTestCase.getTestDirectoryFile();
+ final FileObject baseFile = manager.toFileObject(baseDir);
+ return manager.createVirtualFileSystem(baseFile);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/url/test/UrlHttpProviderTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/url/test/UrlHttpProviderTestCase.java
new file mode 100644
index 0000000..201485e
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/url/test/UrlHttpProviderTestCase.java
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.url.test;
+
+import java.io.File;
+
+import junit.framework.Test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.url.UrlFileProvider;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+
+/**
+ * Test cases for the generic provider.
+ */
+public class UrlHttpProviderTestCase
+ extends AbstractProviderTestConfig
+{
+ public static Test suite() throws Exception
+ {
+ return new ProviderTestSuite(new UrlHttpProviderTestCase());
+ }
+
+ /**
+ * Prepares the file system manager. This implementation does nothing.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager)
+ throws Exception
+ {
+ manager.addProvider("http", new UrlFileProvider());
+ }
+
+ /**
+ * Returns the base folder for tests.
+ */
+ @Override
+ public FileObject getBaseTestFolder(final FileSystemManager manager)
+ throws Exception
+ {
+ final File baseDir = AbstractVfsTestCase.getTestDirectoryFile();
+ return manager.resolveFile(baseDir.toURI().toURL().toExternalForm());
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/url/test/UrlProviderHttpTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/url/test/UrlProviderHttpTestCase.java
new file mode 100644
index 0000000..031f205
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/url/test/UrlProviderHttpTestCase.java
@@ -0,0 +1,134 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.url.test;
+
+import java.io.File;
+import java.io.IOException;
+
+import junit.framework.Test;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.url.UrlFileProvider;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+import org.apache.commons.vfs2.util.FreeSocketPortUtil;
+import org.apache.commons.vfs2.util.NHttpServer;
+
+/**
+ * Test cases for HTTP with the default provider.
+ *
+ */
+public class UrlProviderHttpTestCase extends AbstractProviderTestConfig
+{
+ private static NHttpServer Server;
+
+ private static int SocketPort;
+
+ private static final String TEST_URI = "test.http.uri";
+
+ /**
+ * Use %40 for @ in URLs
+ */
+ private static String ConnectionUri;
+
+ private static String getSystemTestUriOverride()
+ {
+ return System.getProperty(TEST_URI);
+ }
+
+ /**
+ * Creates and starts an embedded Apache HTTP Server ().
+ *
+ * @throws Exception
+ */
+ private static void setUpClass() throws Exception
+ {
+ Server = new NHttpServer();
+ if (!Server.run(SocketPort, new File(getTestDirectory()), 5000))
+ {
+ throw new IllegalStateException("The embedded HTTP server has not completed startup, increase wait time");
+ }
+ }
+
+ public static Test suite() throws Exception
+ {
+ return new ProviderTestSuite(new UrlProviderHttpTestCase())
+ {
+ @Override
+ protected void setUp() throws Exception
+ {
+ if (getSystemTestUriOverride() == null)
+ {
+ setUpClass();
+ }
+ super.setUp();
+ }
+
+ @Override
+ protected void tearDown() throws Exception
+ {
+ tearDownClass();
+ super.tearDown();
+ }
+ };
+ }
+
+ /**
+ * Stops the embedded Apache HTTP Server ().
+ *
+ * @throws IOException
+ */
+ private static void tearDownClass() throws IOException
+ {
+ if (Server != null)
+ {
+ Server.stop();
+ }
+ }
+
+ public UrlProviderHttpTestCase() throws IOException
+ {
+ SocketPort = FreeSocketPortUtil.findFreeLocalPort();
+ // Use %40 for @ in a URL
+ ConnectionUri = "http://localhost:" + SocketPort;
+ }
+
+ /**
+ * Returns the base folder for tests.
+ */
+ @Override
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ String uri = getSystemTestUriOverride();
+ if (uri == null)
+ {
+ uri = ConnectionUri;
+ }
+ return manager.resolveFile(uri);
+ }
+
+ /**
+ * Prepares the file system manager.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager) throws Exception
+ {
+ manager.addProvider("http", new UrlFileProvider());
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/url/test/UrlProviderTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/url/test/UrlProviderTestCase.java
new file mode 100644
index 0000000..6f36b47
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/url/test/UrlProviderTestCase.java
@@ -0,0 +1,62 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.url.test;
+
+import java.io.File;
+
+import junit.framework.Test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.url.UrlFileProvider;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+
+/**
+ * Test cases for the generic provider.
+ */
+public class UrlProviderTestCase
+ extends AbstractProviderTestConfig
+{
+ public static Test suite() throws Exception
+ {
+ return new ProviderTestSuite(new UrlProviderTestCase());
+ }
+
+ /**
+ * Prepares the file system manager. This implementation does nothing.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager)
+ throws Exception
+ {
+ manager.addProvider("file", new UrlFileProvider());
+ }
+
+ /**
+ * Returns the base folder for tests.
+ */
+ @Override
+ public FileObject getBaseTestFolder(final FileSystemManager manager)
+ throws Exception
+ {
+ final File baseDir = AbstractVfsTestCase.getTestDirectoryFile();
+ return manager.resolveFile(baseDir.toURI().toURL().toExternalForm());
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/webdav/test/JackrabbitMain.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/webdav/test/JackrabbitMain.java
new file mode 100644
index 0000000..f3684fb
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/webdav/test/JackrabbitMain.java
@@ -0,0 +1,294 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.commons.vfs2.provider.webdav.test;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.URL;
+import java.util.Collections;
+import java.util.Enumeration;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.GnuParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+import org.apache.commons.io.IOUtils;
+import org.apache.jackrabbit.servlet.jackrabbit.JackrabbitRepositoryServlet;
+import org.apache.jackrabbit.standalone.Main;
+import org.apache.log4j.AppenderSkeleton;
+import org.apache.log4j.ConsoleAppender;
+import org.apache.log4j.FileAppender;
+import org.apache.log4j.Layout;
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+import org.apache.log4j.PatternLayout;
+import org.apache.log4j.Priority;
+import org.mortbay.jetty.Connector;
+import org.mortbay.jetty.NCSARequestLog;
+import org.mortbay.jetty.Server;
+import org.mortbay.jetty.bio.SocketConnector;
+import org.mortbay.jetty.handler.RequestLogHandler;
+import org.mortbay.jetty.servlet.ServletHolder;
+import org.mortbay.jetty.webapp.WebAppContext;
+
+/**
+ * Manages a Jackrabbit server instance.
+ *
+ * Copied and minimally changed from Jackrabbit's Main class in 1.5.2 to add a shutdown method.
+ *
+ * @since 2.1
+ */
+class JackrabbitMain
+{
+
+ /**
+ * @param args
+ */
+ public static void main(final String[] args) throws Exception
+ {
+ new JackrabbitMain(args).run();
+ }
+
+ private final Options options = new Options();
+
+ private final CommandLine command;
+
+ private final RequestLogHandler accessLog = new RequestLogHandler();
+
+ private final WebAppContext webapp = new WebAppContext();
+
+ private final Connector connector = new SocketConnector();
+
+ private final Server server = new Server();
+
+ private FileAppender jackrabbitAppender;
+ private FileAppender jettyAppender;
+
+
+ public JackrabbitMain(final String[] args) throws ParseException
+ {
+ options.addOption("?", "help", false, "print this message");
+ options.addOption("n", "notice", false, "print copyright notices");
+ options.addOption("l", "license", false, "print license information");
+
+ options.addOption("q", "quiet", false, "disable console output");
+ options.addOption("d", "debug", false, "enable debug logging");
+
+ options.addOption("h", "host", true, "IP address of the HTTP server");
+ options.addOption("p", "port", true, "TCP port of the HTTP server (8080)");
+ options.addOption("f", "file", true, "location of this jar file");
+ options.addOption("r", "repo", true, "repository directory (jackrabbit)");
+ options.addOption("c", "conf", true, "repository configuration file");
+
+ command = new GnuParser().parse(options, args);
+ }
+
+ private void copyToOutput(final String resource) throws IOException
+ {
+ final InputStream stream = JackrabbitMain.class.getResourceAsStream(resource);
+ try
+ {
+ IOUtils.copy(stream, System.out);
+ } finally
+ {
+ stream.close();
+ }
+ }
+
+ private void message(final String message)
+ {
+ if (!command.hasOption("quiet"))
+ {
+ System.out.println(message);
+ }
+ }
+
+ private void prepareAccessLog(final File log)
+ {
+ final NCSARequestLog ncsa = new NCSARequestLog(new File(log, "access.log.yyyy_mm_dd").getPath());
+ ncsa.setFilenameDateFormat("yyyy-MM-dd");
+ accessLog.setRequestLog(ncsa);
+ }
+
+ private void prepareConnector()
+ {
+ final String port = command.getOptionValue("port", "8080");
+ connector.setPort(Integer.parseInt(port));
+ final String host = command.getOptionValue("host");
+ if (host != null)
+ {
+ connector.setHost(host);
+ }
+ }
+
+ private void prepareServerLog(final File log) throws IOException
+ {
+ final Layout layout = new PatternLayout("%d{dd.MM.yyyy HH:mm:ss} *%-5p* %c{1}: %m%n");
+
+ final Logger jackrabbitLog = Logger.getRootLogger();
+ jackrabbitAppender = new FileAppender(layout, new File(log, "jackrabbit.log").getPath());
+ jackrabbitAppender.setThreshold(Level.ALL);
+ jackrabbitLog.addAppender(jackrabbitAppender);
+
+ final Logger jettyLog = Logger.getLogger("org.mortbay.log");
+ jettyAppender = new FileAppender(layout, new File(log, "jetty.log").getPath());
+ jettyAppender.setThreshold(Level.ALL);
+ jettyLog.addAppender(jettyAppender);
+ jettyLog.setAdditivity(false);
+
+ System.setProperty("derby.stream.error.file", new File(log, "derby.log").getPath());
+ }
+
+ private void prepareShutdown()
+ {
+ Runtime.getRuntime().addShutdownHook(new Thread()
+ {
+ @Override
+ public void run()
+ {
+ try
+ {
+ shutdown();
+ } catch (final Exception e)
+ {
+ e.printStackTrace();
+ }
+ }
+
+ });
+ }
+
+ private void prepareWebapp(final File file, final File repository, final File tmp)
+ {
+ webapp.setContextPath("/");
+ webapp.setWar(file.getPath());
+ webapp.setClassLoader(JackrabbitMain.class.getClassLoader());
+ // we use a modified web.xml which has some servlets remove (which produce random empty directories)
+ URL res = getResource("/jcrweb.xml");
+ if (res != null)
+ webapp.setDescriptor(res.toString());
+ webapp.setExtractWAR(false);
+ webapp.setTempDirectory(tmp);
+
+ final ServletHolder servlet = new ServletHolder(JackrabbitRepositoryServlet.class);
+ servlet.setInitOrder(1);
+ servlet.setInitParameter("repository.home", repository.getAbsolutePath());
+ final String conf = command.getOptionValue("conf");
+ if (conf != null)
+ {
+ servlet.setInitParameter("repository.config", conf);
+ }
+ webapp.addServlet(servlet, "/repository.properties");
+ }
+
+ /** Try to load a resource with various classloaders. */
+ private URL getResource(String name)
+ {
+ URL res = Thread.currentThread().getContextClassLoader().getResource(name);
+ if (res == null)
+ {
+ res = getClass().getResource(name);
+ }
+ return res; // might be null
+ }
+
+ public void run() throws Exception
+ {
+ String defaultFile = "jackrabbit-standalone.jar";
+ final URL location = Main.class.getProtectionDomain().getCodeSource().getLocation();
+ if (location != null && "file".equals(location.getProtocol()))
+ {
+ final File file = new File(location.getPath());
+ if (file.isFile())
+ {
+ defaultFile = location.getPath();
+ }
+ }
+ final File file = new File(command.getOptionValue("file", defaultFile));
+
+ if (command.hasOption("help"))
+ {
+ final HelpFormatter formatter = new HelpFormatter();
+ formatter.printHelp("java -jar " + file.getName(), options, true);
+ } else if (command.hasOption("notice"))
+ {
+ copyToOutput("/META-INF/NOTICE.txt");
+ } else if (command.hasOption("license"))
+ {
+ copyToOutput("/META-INF/LICENSE.txt");
+ } else
+ {
+ message("Welcome to Apache Jackrabbit!");
+ message("-------------------------------");
+
+ final File repository = new File(command.getOptionValue("repo", "target/test/jackrabbit"));
+ message("Using repository directory " + repository);
+ repository.mkdirs();
+ final File tmp = new File(repository, "tmp");
+ tmp.mkdir();
+ final File log = new File(repository, "log");
+ log.mkdir();
+
+ message("Writing log messages to " + log);
+ prepareServerLog(log);
+
+ message("Starting the server...");
+ prepareWebapp(file, repository, tmp);
+ accessLog.setHandler(webapp);
+ prepareAccessLog(log);
+ server.setHandler(accessLog);
+
+ prepareConnector();
+ server.addConnector(connector);
+ prepareShutdown();
+
+ try
+ {
+ server.start();
+
+ String host = connector.getHost();
+ if (host == null)
+ {
+ host = "localhost";
+ }
+ message("Apache Jackrabbit is now running at " + "http://" + host + ":" + connector.getPort() + "/");
+ } catch (final Throwable t)
+ {
+ System.err.println("Unable to start the server: " + t.getMessage());
+ System.exit(1);
+ }
+ }
+ }
+
+ public void shutdown() throws Exception, InterruptedException
+ {
+ message("Shutting down the server...");
+ server.setGracefulShutdown(5);
+ server.stop();
+ Logger.getRootLogger().removeAppender(jackrabbitAppender);
+ Logger.getLogger("org.mortbay.log").removeAppender(jettyAppender);
+ jackrabbitAppender.close();
+ jettyAppender.close();
+ server.join();
+ message("-------------------------------");
+ message("Goodbye from Apache Jackrabbit!");
+ }
+
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/webdav/test/JcrUtils.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/webdav/test/JcrUtils.java
new file mode 100644
index 0000000..10ccbc8
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/webdav/test/JcrUtils.java
@@ -0,0 +1,221 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// COPIED FROM JACKRABBIT 2.4.0
+
+package org.apache.commons.vfs2.provider.webdav.test;
+
+import java.io.InputStream;
+import java.util.Calendar;
+
+import javax.jcr.Node;
+import javax.jcr.RepositoryException;
+import javax.jcr.Value;
+
+/**
+ * Collection of static utility methods for use with the JCR 1.0 API and Apache Jackrabbit 1.5.2.
+ *
+ * Copied, adapted and pruned down from Jackrabbit 2.4.0.
+ *
+ * @since 2.1
+ */
+class JcrUtils
+{
+
+ private static final String NodeType_NT_RESOURCE = "nt:resource";
+
+ private static final String Node_JCR_CONTENT = "jcr:content";
+
+ private static final String NodeType_NT_FOLDER = "nt:folder";
+
+ private static final String NodeType_NT_FILE = "nt:file";
+
+ private static final String Property_JCR_MIMETYPE = "jcr:mimeType";
+
+ private static final String Property_JCR_ENCODING = "jcr:encoding";
+
+ private static final String Property_JCR_LAST_MODIFIED = "jcr:lastModified";
+
+ private static final String Property_JCR_DATA = "jcr:data";
+
+ /**
+ * Returns the named child of the given node, creating it as an nt:folder node if it does not already exist. The caller is expected to
+ * take care of saving or discarding any transient changes.
+ * <p>
+ * Note that the type of the returned node is <em>not</em> guaranteed to match nt:folder in case the node already existed. The caller
+ * can use an explicit {@link Node#isNodeType(String)} check if needed, or simply use a data-first approach and not worry about the node
+ * type until a constraint violation is encountered.
+ *
+ * @param parent
+ * parent node
+ * @param name
+ * name of the child node
+ * @return the child node
+ * @throws RepositoryException
+ * if the child node can not be accessed or created
+ */
+ public static Node getOrAddFolder(final Node parent, final String name) throws RepositoryException
+ {
+ return getOrAddNode(parent, name, NodeType_NT_FOLDER);
+ }
+
+ /**
+ * Returns the named child of the given node, creating the child if it does not already exist. If the child node gets added, then it is
+ * created with the given node type. The caller is expected to take care of saving or discarding any transient changes.
+ *
+ * @see Node#getNode(String)
+ * @see Node#addNode(String, String)
+ * @see Node#isNodeType(String)
+ * @param parent
+ * parent node
+ * @param name
+ * name of the child node
+ * @param type
+ * type of the child node, ignored if the child already exists
+ * @return the child node
+ * @throws RepositoryException
+ * if the child node can not be accessed or created
+ */
+ public static Node getOrAddNode(final Node parent, final String name, final String type) throws RepositoryException
+ {
+ if (parent.hasNode(name))
+ {
+ return parent.getNode(name);
+ } else
+ {
+ return parent.addNode(name, type);
+ }
+ }
+
+ /**
+ * Creates or updates the named child of the given node. If the child does not already exist, then it is created using the nt:file node
+ * type. This file child node is returned from this method.
+ * <p>
+ * If the file node does not already contain a jcr:content child, then one is created using the nt:resource node type. The following
+ * properties are set on the jcr:content node:
+ * <dl>
+ * <dt>jcr:mimeType</dt>
+ * <dd>media type</dd>
+ * <dt>jcr:encoding (optional)</dt>
+ * <dd>charset parameter of the media type, if any</dd>
+ * <dt>jcr:lastModified</dt>
+ * <dd>current time</dd>
+ * <dt>jcr:data</dt>
+ * <dd>binary content</dd>
+ * </dl>
+ * <p>
+ * Note that the types of the returned node or the jcr:content child are <em>not</em> guaranteed to match nt:file and nt:resource in
+ * case the nodes already existed. The caller can use an explicit {@link Node#isNodeType(String)} check if needed, or simply use a
+ * data-first approach and not worry about the node type until a constraint violation is encountered.
+ * <p>
+ * The given binary content stream is closed by this method.
+ *
+ * @param parent
+ * parent node
+ * @param name
+ * name of the file
+ * @param mime
+ * media type of the file
+ * @param data
+ * binary content of the file
+ * @return the child node
+ * @throws RepositoryException
+ * if the child node can not be created or updated
+ */
+ public static Node putFile(final Node parent, final String name, final String mime, final InputStream data) throws RepositoryException
+ {
+ return putFile(parent, name, mime, data, Calendar.getInstance());
+ }
+
+ /**
+ * Creates or updates the named child of the given node. If the child does not already exist, then it is created using the nt:file node
+ * type. This file child node is returned from this method.
+ * <p>
+ * If the file node does not already contain a jcr:content child, then one is created using the nt:resource node type. The following
+ * properties are set on the jcr:content node:
+ * <dl>
+ * <dt>jcr:mimeType</dt>
+ * <dd>media type</dd>
+ * <dt>jcr:encoding (optional)</dt>
+ * <dd>charset parameter of the media type, if any</dd>
+ * <dt>jcr:lastModified</dt>
+ * <dd>date of last modification</dd>
+ * <dt>jcr:data</dt>
+ * <dd>binary content</dd>
+ * </dl>
+ * <p>
+ * Note that the types of the returned node or the jcr:content child are <em>not</em> guaranteed to match nt:file and nt:resource in
+ * case the nodes already existed. The caller can use an explicit {@link Node#isNodeType(String)} check if needed, or simply use a
+ * data-first approach and not worry about the node type until a constraint violation is encountered.
+ * <p>
+ * The given binary content stream is closed by this method.
+ *
+ * @param parent
+ * parent node
+ * @param name
+ * name of the file
+ * @param mime
+ * media type of the file
+ * @param data
+ * binary content of the file
+ * @param date
+ * date of last modification
+ * @return the child node
+ * @throws RepositoryException
+ * if the child node can not be created or updated
+ */
+ public static Node putFile(final Node parent, final String name, final String mime, final InputStream data, final Calendar date)
+ throws RepositoryException
+ {
+ final Value binary = parent.getSession().getValueFactory().createValue(data);
+ try
+ {
+ final Node file = getOrAddNode(parent, name, NodeType_NT_FILE);
+ final Node content = getOrAddNode(file, Node_JCR_CONTENT, NodeType_NT_RESOURCE);
+
+ content.setProperty(Property_JCR_MIMETYPE, mime);
+ final String[] parameters = mime.split(";");
+ for (int i = 1; i < parameters.length; i++)
+ {
+ final int equals = parameters[i].indexOf('=');
+ if (equals != -1)
+ {
+ final String parameter = parameters[i].substring(0, equals);
+ if ("charset".equalsIgnoreCase(parameter.trim()))
+ {
+ content.setProperty(Property_JCR_ENCODING, parameters[i].substring(equals + 1).trim());
+ }
+ }
+ }
+
+ content.setProperty(Property_JCR_LAST_MODIFIED, date);
+ content.setProperty(Property_JCR_DATA, binary);
+ return file;
+ } finally
+ {
+ // JCR 2.0 API:
+ // binary.dispose();
+ }
+ }
+
+ /**
+ * Private constructor to prevent instantiation of this class.
+ */
+ private JcrUtils()
+ {
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/webdav/test/WebdavProviderTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/webdav/test/WebdavProviderTestCase.java
new file mode 100644
index 0000000..f9d7c52
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/webdav/test/WebdavProviderTestCase.java
@@ -0,0 +1,380 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.webdav.test;
+
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+import javax.jcr.Node;
+import javax.jcr.NodeIterator;
+import javax.jcr.Property;
+import javax.jcr.PropertyIterator;
+import javax.jcr.RepositoryException;
+import javax.jcr.Session;
+import javax.jcr.SimpleCredentials;
+import javax.jcr.Value;
+
+import junit.framework.Test;
+
+import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
+import org.apache.commons.io.FileUtils;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.temp.TemporaryFileProvider;
+import org.apache.commons.vfs2.provider.webdav.WebdavFileProvider;
+import org.apache.commons.vfs2.provider.webdav.WebdavFileSystemConfigBuilder;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+import org.apache.commons.vfs2.util.FreeSocketPortUtil;
+import org.apache.jackrabbit.core.TransientRepository;
+import org.apache.log4j.Level;
+import org.apache.log4j.Logger;
+
+/**
+ * Test cases for the WebDAV provider.
+ *
+ */
+public class WebdavProviderTestCase extends AbstractProviderTestConfig
+{
+ private static final char[] PASSWORD = new char[0];
+
+ private static final String USER_ID = "admin";
+
+ private static int SocketPort;
+
+ private static final String TEST_URI = "test.webdav.uri";
+
+ private static JackrabbitMain JrMain;
+
+ /**
+ * Use %40 for @ in URLs
+ */
+ private static String ConnectionUri;
+
+ private static File RepoDirectory;
+
+ private static boolean DEBUG = Boolean.getBoolean("WebdavProviderTestCase.Debug");
+
+ static File createTempDirectory() throws IOException
+ {
+ // create base folder
+ final File base = new File("./target/test").getCanonicalFile();
+ base.mkdirs();
+
+ final File tempFile = File.createTempFile("WebdavProviderTestCase_", ".tmp", base);
+
+ if (!tempFile.delete())
+ {
+ throw new IOException("Could not delete temp file: " + tempFile.getAbsolutePath());
+ }
+
+ if (!tempFile.mkdir())
+ {
+ throw new IOException("Could not create temp directory: " + tempFile.getAbsolutePath());
+ }
+
+ if (DEBUG)
+ System.out.println("Working in " + tempFile);
+
+ return tempFile;
+ }
+
+ private static void dump(final File repoDirectory) throws Exception
+ {
+ final TransientRepository repository = getTransientRepository(repoDirectory);
+ try
+ {
+ final Session session = getSession(repository);
+ message("Root node dump:");
+ dump(session.getRootNode());
+ session.logout();
+ } finally
+ {
+ repository.shutdown();
+ }
+ }
+
+ /** Recursively outputs the contents of the given node. */
+ private static void dump(final Node node) throws RepositoryException
+ {
+ // First output the node path
+ message(node.getPath());
+ // Skip the virtual (and large!) jcr:system subtree
+ if (node.getName().equals("jcr:system"))
+ {
+ return;
+ }
+
+ if (node.getName().equals("jcr:content"))
+ {
+ return;
+ }
+
+ // Then output the properties
+ final PropertyIterator properties = node.getProperties();
+ while (properties.hasNext())
+ {
+ final Property property = properties.nextProperty();
+ if (property.getDefinition().isMultiple())
+ {
+ // A multi-valued property, print all values
+ final Value[] values = property.getValues();
+ for (final Value value : values)
+ {
+ message(property.getPath() + " = " + value.getString());
+ }
+ } else
+ {
+ // A single-valued property
+ message(property.getPath() + " = " + property.getString());
+ }
+ }
+
+ // Finally output all the child nodes recursively
+ final NodeIterator nodes = node.getNodes();
+ while (nodes.hasNext())
+ {
+ dump(nodes.nextNode());
+ }
+ }
+
+ private static Session getSession(final TransientRepository repository) throws RepositoryException
+ {
+ return repository.login(new SimpleCredentials(USER_ID, PASSWORD));
+ }
+
+ private static String getSystemTestUriOverride()
+ {
+ return System.getProperty(TEST_URI);
+ }
+
+ private static TransientRepository getTransientRepository(final File repoDirectory) throws IOException
+ {
+ // Jackrabbit 1.6:
+ // TransientRepository repository = new TransientRepository(repoDirectory);
+ // Jackrabbit 1.5.2:
+ return new TransientRepository(new File(repoDirectory, "repository.xml").toString(), repoDirectory.toString());
+ }
+
+ private static void importFiles(final File repoDirectory, final File sourceDir) throws Exception
+ {
+ final TransientRepository repository = getTransientRepository(repoDirectory);
+ try
+ {
+ final Session session = getSession(repository);
+ importFiles(session.getRootNode(), sourceDir);
+ session.save();
+ session.logout();
+ } finally
+ {
+ repository.shutdown();
+ }
+ }
+
+ private static void importFiles(final Node parent, final File sourceDir) throws RepositoryException, IOException
+ {
+ final File[] files = sourceDir.listFiles();
+ for (final File file : files)
+ {
+ if (file.isFile())
+ {
+ final InputStream data = new FileInputStream(file);
+ try
+ {
+ message("Importing file " + file);
+ JcrUtils.putFile(parent, file.getName(), "application/octet-stream", data);
+ } finally
+ {
+ data.close();
+ }
+ } else if (file.isDirectory())
+ {
+ message("Importing folder " + file);
+ final Node folder = JcrUtils.getOrAddFolder(parent, file.getName());
+ importFiles(folder, file);
+ }
+ }
+ }
+
+ private static void message(final IOException e)
+ {
+ if (DEBUG)
+ {
+ e.printStackTrace();
+ }
+ }
+
+ private static void message(final String string)
+ {
+ if (DEBUG)
+ {
+ System.out.println(string);
+ }
+ }
+
+ /**
+ * Creates and starts an embedded Apache WebDAV Server (Jackrabbit).
+ *
+ * @throws Exception
+ */
+ private static void setUpClass() throws Exception
+ {
+ // Create temp dir for repo
+ RepoDirectory = createTempDirectory();
+ message("Created temp directory " + RepoDirectory);
+ // Populate repo
+ importFiles(RepoDirectory, new File(getTestDirectory()));
+ dump(RepoDirectory);
+ // Start server with temp repo
+ startJackrabbit(RepoDirectory);
+ message("Returned from org.apache.jackrabbit.standalone.Main " + SocketPort);
+ }
+
+ /**
+ * Starts an embedded Apache Jackrabbit server.
+ *
+ * @param repoDirectory
+ * @throws Exception
+ */
+ private static void startJackrabbit(final File repoDirectory) throws Exception
+ {
+ boolean quiet = false;
+ if (!DEBUG)
+ {
+ Logger.getLogger("org.apache.jackrabbit").setLevel(Level.WARN);
+ Logger.getLogger("org.apache.commons.httpclient").setLevel(Level.ERROR);
+ Logger.getLogger("org.apache.commons.vfs2").setLevel(Level.WARN);
+ Logger.getLogger("org.mortbay").setLevel(Level.WARN);
+ quiet = true;
+ }
+ JrMain = new JackrabbitMain(new String[]
+ { "--port", Integer.toString(SocketPort), "--repo", repoDirectory.toString(), quiet ? "--quiet" : "" });
+ JrMain.run();
+ }
+
+ public static Test suite() throws Exception
+ {
+ return new ProviderTestSuite(new WebdavProviderTestCase())
+ {
+ @Override
+ protected void setUp() throws Exception
+ {
+ if (getSystemTestUriOverride() == null)
+ {
+ setUpClass();
+ }
+ super.setUp();
+ }
+
+ @Override
+ protected void tearDown() throws Exception
+ {
+ tearDownClass();
+ super.tearDown();
+ }
+ };
+ }
+
+ /**
+ * Tears down resources for this test case.
+ * <ol>
+ * <li>Shuts down the embedded Jackrabbit</li>
+ * <li>Extra clean up for org.apache.commons.httpclient.MultiThreadedHttpConnectionManager</li>
+ * <li>Remove temporary repository directory.</li>
+ * </ol>
+ * Stops the embedded Apache WebDAV Server.
+ *
+ * @throws Exception
+ * @throws
+ */
+ private static void tearDownClass() throws Exception
+ {
+ // Main JR shutdown
+ JrMain.shutdown();
+ // WARN logged because one thread is still there, so clean up explicitly.
+ MultiThreadedHttpConnectionManager.shutdownAll();
+
+ if (DEBUG)
+ {
+ message("Skipping cleanup of " + RepoDirectory);
+ return;
+ }
+
+ // Remove repo dir
+ try
+ {
+ message("Deleting temp directory " + RepoDirectory);
+ FileUtils.deleteDirectory(RepoDirectory);
+ } catch (final IOException e)
+ {
+ message(e);
+ if (RepoDirectory.exists())
+ {
+ message("Directory will be deleted on VM exit " + RepoDirectory);
+ RepoDirectory.deleteOnExit();
+ }
+ }
+ }
+
+ public WebdavProviderTestCase() throws IOException
+ {
+ SocketPort = FreeSocketPortUtil.findFreeLocalPort();
+ message("FreeSocketPortUtil.findFreeLocalPort() = " + SocketPort);
+ // Use %40 for @ in a URL
+ // Any user id and password will do with the default Jackrabbit set up.
+ ConnectionUri = String.format("webdav://%s@localhost:%d/repository/default", USER_ID, SocketPort);
+ }
+
+ /**
+ * Returns the base folder for tests.
+ */
+ @Override
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ String uri = getSystemTestUriOverride();
+ if (uri == null)
+ {
+ uri = ConnectionUri;
+ }
+ final WebdavFileSystemConfigBuilder builder = (WebdavFileSystemConfigBuilder) manager
+ .getFileSystemConfigBuilder("webdav");
+ final FileSystemOptions opts = new FileSystemOptions();
+ builder.setRootURI(opts, uri);
+ return manager.resolveFile(uri, opts);
+ }
+
+ @Override
+ public boolean isFileSystemRootAccessible()
+ {
+ return false;
+ }
+
+ /**
+ * Prepares the file system manager.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager) throws Exception
+ {
+ manager.addProvider("webdav", new WebdavFileProvider());
+ manager.addProvider("tmp", new TemporaryFileProvider());
+ }
+
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/webdav/test/WebdavProviderTestSuite.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/webdav/test/WebdavProviderTestSuite.java
new file mode 100644
index 0000000..f9f1a5e
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/webdav/test/WebdavProviderTestSuite.java
@@ -0,0 +1,92 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.webdav.test;
+
+import org.apache.commons.vfs2.test.ContentTests;
+import org.apache.commons.vfs2.test.LastModifiedTests;
+import org.apache.commons.vfs2.test.NamingTests;
+import org.apache.commons.vfs2.test.ProviderCacheStrategyTests;
+import org.apache.commons.vfs2.test.ProviderDeleteTests;
+import org.apache.commons.vfs2.test.ProviderRandomReadTests;
+import org.apache.commons.vfs2.test.ProviderRandomReadWriteTests;
+import org.apache.commons.vfs2.test.ProviderReadTests;
+import org.apache.commons.vfs2.test.ProviderRenameTests;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+import org.apache.commons.vfs2.test.ProviderWriteAppendTests;
+import org.apache.commons.vfs2.test.ProviderWriteTests;
+import org.apache.commons.vfs2.test.UriTests;
+import org.apache.commons.vfs2.test.UrlStructureTests;
+import org.apache.commons.vfs2.test.UrlTests;
+
+/**
+ * The suite of tests for a file system.
+ */
+public class WebdavProviderTestSuite extends ProviderTestSuite
+{
+ /**
+ * Adds the tests for a file system to this suite.
+ */
+ public WebdavProviderTestSuite(final ProviderTestConfig providerConfig) throws Exception
+ {
+ this(providerConfig, "", false, false);
+ }
+
+ /**
+ * Adds the tests for a file system to this suite. Provider has an empty directory.
+ */
+ public WebdavProviderTestSuite(final ProviderTestConfig providerConfig,
+ final boolean addEmptyDir) throws Exception
+ {
+ this(providerConfig, "", false, addEmptyDir);
+ }
+
+
+
+ protected WebdavProviderTestSuite(final ProviderTestConfig providerConfig,
+ final String prefix,
+ final boolean nested,
+ final boolean addEmptyDir)
+ throws Exception
+ {
+ super(providerConfig, prefix, nested, addEmptyDir);
+ }
+
+ /**
+ * Adds base tests - excludes the nested test cases.
+ */
+ @Override
+ protected void addBaseTests() throws Exception
+ {
+ addTests(ProviderCacheStrategyTests.class);
+ addTests(UriTests.class);
+ addTests(NamingTests.class);
+ addTests(ContentTests.class);
+ addTests(ProviderReadTests.class);
+ addTests(ProviderRandomReadTests.class);
+ addTests(ProviderWriteTests.class);
+ addTests(ProviderWriteAppendTests.class);
+ addTests(ProviderRandomReadWriteTests.class);
+ addTests(ProviderRenameTests.class);
+ addTests(ProviderDeleteTests.class);
+ addTests(LastModifiedTests.class);
+ addTests(UrlTests.class);
+ addTests(UrlStructureTests.class);
+ // The class loader test requires the classes be uploaded to the webdav repo.
+ //addTests(VfsClassLoaderTests.class);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/webdav/test/WebdavVersioningTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/webdav/test/WebdavVersioningTests.java
new file mode 100644
index 0000000..5eecb3b
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/webdav/test/WebdavVersioningTests.java
@@ -0,0 +1,165 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.webdav.test;
+
+import java.io.OutputStream;
+import java.util.Map;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.Selectors;
+import org.apache.commons.vfs2.provider.URLFileName;
+import org.apache.commons.vfs2.provider.webdav.WebdavFileSystemConfigBuilder;
+import org.apache.commons.vfs2.test.AbstractProviderTestCase;
+import org.apache.jackrabbit.webdav.version.DeltaVConstants;
+import org.apache.jackrabbit.webdav.version.VersionControlledResource;
+
+/**
+ * Test to verify Webdav Versioning support
+ */
+public class WebdavVersioningTests extends AbstractProviderTestCase
+{
+ /**
+ */
+ public void testVersioning() throws Exception
+ {
+ final FileObject scratchFolder = createScratchFolder();
+ final FileSystemOptions opts = scratchFolder.getFileSystem().getFileSystemOptions();
+ final WebdavFileSystemConfigBuilder builder =
+ (WebdavFileSystemConfigBuilder)getManager().getFileSystemConfigBuilder("webdav");
+ builder.setVersioning(opts, true);
+ final FileObject file = getManager().resolveFile(scratchFolder, "file1.txt", opts);
+ final FileSystemOptions newOpts = file.getFileSystem().getFileSystemOptions();
+ assertTrue(opts == newOpts);
+ assertTrue(builder.isVersioning(newOpts));
+ assertTrue(!file.exists());
+ file.createFile();
+ assertTrue(file.exists());
+ assertSame(FileType.FILE, file.getType());
+ assertTrue(file.isFile());
+ assertEquals(0, file.getContent().getSize());
+ assertFalse(file.isExecutable());
+ assertFalse(file.isHidden());
+ assertTrue(file.isReadable());
+ assertTrue(file.isWriteable());
+ Map<?, ?> map = file.getContent().getAttributes();
+ final String name = ((URLFileName)file.getName()).getUserName();
+ assertTrue(map.containsKey(DeltaVConstants.CREATOR_DISPLAYNAME.toString()));
+ if (name != null)
+ {
+ assertEquals(name, map.get(DeltaVConstants.CREATOR_DISPLAYNAME.toString()));
+ }
+ assertTrue(map.containsKey(VersionControlledResource.CHECKED_IN.toString()));
+
+ // Create the source file
+ final String content = "Here is some sample content for the file. Blah Blah Blah.";
+
+ final OutputStream os = file.getContent().getOutputStream();
+ try
+ {
+ os.write(content.getBytes("utf-8"));
+ }
+ finally
+ {
+ os.close();
+ }
+ assertSameContent(content, file);
+ map = file.getContent().getAttributes();
+ assertTrue(map.containsKey(DeltaVConstants.CREATOR_DISPLAYNAME.toString()));
+ if (name != null)
+ {
+ assertEquals(name, map.get(DeltaVConstants.CREATOR_DISPLAYNAME.toString()));
+ }
+ assertTrue(map.containsKey(VersionControlledResource.CHECKED_IN.toString()));
+ builder.setVersioning(opts, false);
+ }
+ /**
+ */
+ public void testVersioningWithCreator() throws Exception
+ {
+ final FileObject scratchFolder = createScratchFolder();
+ final FileSystemOptions opts = scratchFolder.getFileSystem().getFileSystemOptions();
+ final WebdavFileSystemConfigBuilder builder =
+ (WebdavFileSystemConfigBuilder)getManager().getFileSystemConfigBuilder("webdav");
+ builder.setVersioning(opts, true);
+ builder.setCreatorName(opts, "testUser");
+ final FileObject file = getManager().resolveFile(scratchFolder, "file1.txt", opts);
+ final FileSystemOptions newOpts = file.getFileSystem().getFileSystemOptions();
+ assertTrue(opts == newOpts);
+ assertTrue(builder.isVersioning(newOpts));
+ assertTrue(!file.exists());
+ file.createFile();
+ assertTrue(file.exists());
+ assertSame(FileType.FILE, file.getType());
+ assertTrue(file.isFile());
+ assertEquals(0, file.getContent().getSize());
+ assertFalse(file.isExecutable());
+ assertFalse(file.isHidden());
+ assertTrue(file.isReadable());
+ assertTrue(file.isWriteable());
+ Map<?, ?> map = file.getContent().getAttributes();
+ final String name = ((URLFileName)file.getName()).getUserName();
+ assertTrue(map.containsKey(DeltaVConstants.CREATOR_DISPLAYNAME.toString()));
+ assertEquals(map.get(DeltaVConstants.CREATOR_DISPLAYNAME.toString()),"testUser");
+ if (name != null)
+ {
+ assertTrue(map.containsKey(DeltaVConstants.COMMENT.toString()));
+ assertEquals("Modified by user " + name, map.get(DeltaVConstants.COMMENT.toString()));
+ }
+ assertTrue(map.containsKey(VersionControlledResource.CHECKED_IN.toString()));
+
+ // Create the source file
+ final String content = "Here is some sample content for the file. Blah Blah Blah.";
+
+ final OutputStream os = file.getContent().getOutputStream();
+ try
+ {
+ os.write(content.getBytes("utf-8"));
+ }
+ finally
+ {
+ os.close();
+ }
+ assertSameContent(content, file);
+ map = file.getContent().getAttributes();
+ assertTrue(map.containsKey(DeltaVConstants.CREATOR_DISPLAYNAME.toString()));
+ assertEquals(map.get(DeltaVConstants.CREATOR_DISPLAYNAME.toString()),"testUser");
+ if (name != null)
+ {
+ assertTrue(map.containsKey(DeltaVConstants.COMMENT.toString()));
+ assertEquals("Modified by user " + name, map.get(DeltaVConstants.COMMENT.toString()));
+ }
+ assertTrue(map.containsKey(VersionControlledResource.CHECKED_IN.toString()));
+ builder.setVersioning(opts, false);
+ builder.setCreatorName(opts, null);
+ }
+ /**
+ * Sets up a scratch folder for the test to use.
+ */
+ protected FileObject createScratchFolder() throws Exception
+ {
+ final FileObject scratchFolder = getWriteFolder();
+
+ // Make sure the test folder is empty
+ scratchFolder.delete(Selectors.EXCLUDE_SELF);
+ scratchFolder.createFolder();
+
+ return scratchFolder;
+ }
+
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/zip/test/NestedZipTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/zip/test/NestedZipTestCase.java
new file mode 100644
index 0000000..37c3348
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/zip/test/NestedZipTestCase.java
@@ -0,0 +1,72 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.zip.test;
+
+import junit.framework.Test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.zip.ZipFileProvider;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+
+/**
+ * Tests for the Zip file system, using a zip file nested inside another zip file.
+ */
+public class NestedZipTestCase
+ extends AbstractProviderTestConfig
+ implements ProviderTestConfig
+{
+ /**
+ * Creates the test suite for nested zip files.
+ */
+ public static Test suite() throws Exception
+ {
+ return new ProviderTestSuite(new NestedZipTestCase(), true);
+ }
+
+ /**
+ * 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
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ // Locate the base Zip file
+ final String zipFilePath = AbstractVfsTestCase.getTestResource("nested.zip").getAbsolutePath();
+ final String uri = "zip:file:" + zipFilePath + "!/test.zip";
+ final FileObject zipFile = manager.resolveFile(uri);
+
+ // Now build the nested file system
+ final FileObject nestedFS = manager.createFileSystem(zipFile);
+ return nestedFS.resolveFile("/");
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/provider/zip/test/ZipProviderTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/zip/test/ZipProviderTestCase.java
new file mode 100644
index 0000000..18d4335
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/provider/zip/test/ZipProviderTestCase.java
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.zip.test;
+
+import java.io.File;
+
+import junit.framework.Test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.zip.ZipFileProvider;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+
+/**
+ * Tests for the Zip file system.
+ */
+public class ZipProviderTestCase
+ extends AbstractProviderTestConfig
+ implements ProviderTestConfig
+{
+ /**
+ * Creates the test suite for the zip file system.
+ */
+ public static Test suite() throws Exception
+ {
+ return new ProviderTestSuite(new ZipProviderTestCase(), true);
+ }
+
+ /**
+ * 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
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ final File zipFile = AbstractVfsTestCase.getTestResource("test.zip");
+ final String uri = "zip:file:" + zipFile.getAbsolutePath() + "!/";
+ return manager.resolveFile(uri);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/test/AbstractProviderTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/AbstractProviderTestCase.java
new file mode 100644
index 0000000..8f27d07
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/AbstractProviderTestCase.java
@@ -0,0 +1,405 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.net.URLConnection;
+import java.util.Arrays;
+
+import junit.framework.Test;
+import junit.framework.TestCase;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileContent;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.AbstractFileSystem;
+import org.apache.commons.vfs2.provider.local.DefaultLocalFileProvider;
+
+/**
+ * File system test cases, which verifies the structure and naming
+ * functionality.
+ * <p>
+ * Works from a base folder, and assumes a particular structure under
+ * that base folder.
+ */
+public abstract class AbstractProviderTestCase
+ extends AbstractVfsTestCase
+{
+ 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.";
+
+ // Expected contents of test files
+ public static final String TEST_FILE_CONTENT = "A test file.";
+
+ /**
+ * Sets the test method.
+ */
+ public void setMethod(final Method method)
+ {
+ this.method = method;
+ }
+
+ /**
+ * Configures this test.
+ */
+ 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;
+ }
+
+ /**
+ * Returns the file system manager used by this test.
+ */
+ protected DefaultFileSystemManager getManager()
+ {
+ return manager;
+ }
+
+ /**
+ * creates a new uninitialized file system manager
+ * @throws Exception
+ */
+ protected DefaultFileSystemManager createManager() throws Exception
+ {
+ final DefaultFileSystemManager fs = getProviderConfig().getDefaultFileSystemManager();
+ fs.setFilesCache(getProviderConfig().getFilesCache());
+ getProviderConfig().prepare(fs);
+ if (!fs.hasProvider("file"))
+ {
+ fs.addProvider("file", new DefaultLocalFileProvider());
+ }
+ return fs;
+ }
+
+ /**
+ * some provider config do some post-initialization in getBaseTestFolder.
+ * This is a hack to allow access to this code for {@code createManager}
+ */
+ public FileObject getBaseTestFolder(final FileSystemManager fs) throws Exception
+ {
+ return providerConfig.getBaseTestFolder(fs);
+ }
+
+ protected FileSystem getFileSystem()
+ {
+ return getReadFolder().getFileSystem();
+ }
+
+ /**
+ * Returns the base test folder. This is the parent of both the read
+ * test and write test folders.
+ */
+ public FileObject getBaseFolder()
+ {
+ return baseFolder;
+ }
+
+ /**
+ * get the provider configuration
+ */
+ public ProviderTestConfig getProviderConfig()
+ {
+ return providerConfig;
+ }
+
+ /**
+ * Returns the read test folder.
+ */
+ protected FileObject getReadFolder()
+ {
+ return readFolder;
+ }
+
+ /**
+ * 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>
+ * This implementation returns null.
+ */
+ protected Capability[] getRequiredCaps()
+ {
+ return null;
+ }
+
+ /**
+ * Runs the test. This implementation short-circuits the test if the
+ * provider being tested does not have the capabilities required by this
+ * test.
+ * <p>
+ * TODO - Handle negative caps as well - ie, only run a test if the provider does not have certain caps.<br>
+ * TODO - Figure out how to remove the test from the TestResult if the test is skipped.
+ */
+ @Override
+ protected void runTest() throws Throwable
+ {
+ // Check the capabilities
+ final Capability[] caps = getRequiredCaps();
+ if (caps != null)
+ {
+ for (final Capability cap2 : caps)
+ {
+ final Capability cap = cap2;
+ final FileSystem fs = readFolder.getFileSystem();
+ if (!fs.hasCapability(cap))
+ {
+// String name = fs.getClass().getName();
+// int index = name.lastIndexOf('.');
+// String fsName = (index > 0) ? name.substring(index + 1) : name;
+// System.out.println("skipping " + getName() + " because " +
+// fsName + " does not have capability " + cap);
+ return;
+ }
+ }
+ }
+
+ // Provider has all the capabilities - execute the test
+ if (method != null)
+ {
+ try
+ {
+ method.invoke(this, (Object[]) null);
+ }
+ catch (final InvocationTargetException e)
+ {
+ throw e.getTargetException();
+ }
+ }
+ else
+ {
+ super.runTest();
+ }
+
+ if (((AbstractFileSystem) readFolder.getFileSystem()).isOpen())
+ {
+ String name = "unknown";
+ if (method != null)
+ {
+ name = method.getName();
+ }
+
+ throw new IllegalStateException(getClass().getName() + ": filesystem has open streams after: " + name);
+ }
+ }
+
+ /**
+ * 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.
+ */
+ protected void assertSameURLContent(final String expected,
+ final URLConnection connection)
+ throws Exception
+ {
+ // Get file content as a binary stream
+ final byte[] expectedBin = expected.getBytes("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
+ assertTrue("same binary content", Arrays.equals(expectedBin, outstr.toByteArray()));
+ }
+
+ /**
+ * 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.
+ */
+ 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("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
+ assertTrue("same binary content", Arrays.equals(expectedBin, outstr.toByteArray()));
+ }
+
+ /**
+ * Builds the expected structure of the read tests folder.
+ * @throws FileSystemException (possibly)
+ */
+ 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);
+ }
+ };
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/test/AbstractProviderTestConfig.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/AbstractProviderTestConfig.java
new file mode 100644
index 0000000..a7b7221
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/AbstractProviderTestConfig.java
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import org.apache.commons.vfs2.FilesCache;
+import org.apache.commons.vfs2.cache.SoftRefFilesCache;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+
+/**
+ * A partial {@link org.apache.commons.vfs2.test.ProviderTestConfig} implementation.
+ */
+public abstract class AbstractProviderTestConfig extends AbstractProviderTestCase
+ implements ProviderTestConfig
+{
+ private FilesCache cache = null;
+
+ /**
+ * Returns a DefaultFileSystemManager instance (or subclass instance).
+ */
+ @Override
+ public DefaultFileSystemManager getDefaultFileSystemManager() {
+ return new DefaultFileSystemManager();
+ }
+
+ /**
+ * Prepares the file system manager. This implementation does nothing.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager)
+ throws Exception
+ {
+ }
+
+ @Override
+ public FilesCache getFilesCache()
+ {
+ if (cache == null)
+ {
+ // cache = new DefaultFilesCache();
+ cache = new SoftRefFilesCache();
+ }
+
+ return cache;
+ }
+
+ @Override
+ public boolean isFileSystemRootAccessible()
+ {
+ return true;
+ }
+
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/test/AbstractTestSuite.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/AbstractTestSuite.java
new file mode 100644
index 0000000..9278a6d
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/AbstractTestSuite.java
@@ -0,0 +1,376 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import java.io.File;
+import java.lang.reflect.Field;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.List;
+
+import junit.extensions.TestSetup;
+import junit.framework.Protectable;
+import junit.framework.Test;
+import junit.framework.TestResult;
+import junit.framework.TestSuite;
+
+import org.apache.commons.io.FileUtils;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.impl.DefaultFileReplicator;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.impl.PrivilegedFileReplicator;
+import org.apache.commons.vfs2.provider.local.DefaultLocalFileProvider;
+
+/**
+ * The suite of tests for a file system.
+ */
+public abstract class AbstractTestSuite
+ extends TestSetup
+{
+ private final ProviderTestConfig providerConfig;
+ private final String prefix;
+ private TestSuite testSuite;
+
+ private FileObject baseFolder;
+ private FileObject readFolder;
+ private FileObject writeFolder;
+ private DefaultFileSystemManager manager;
+ private File tempDir;
+
+ private Thread[] startThreadSnapshot;
+ private Thread[] endThreadSnapshot;
+ private final boolean addEmptyDir;
+
+ /**
+ * Adds the tests for a file system to this suite.
+ */
+ public AbstractTestSuite(final ProviderTestConfig providerConfig) throws Exception
+ {
+ this(providerConfig, "", false, false);
+ }
+
+ protected AbstractTestSuite(final ProviderTestConfig providerConfig,
+ final String prefix,
+ final boolean nested) throws Exception
+ {
+ this(providerConfig, prefix, nested, false);
+ }
+
+
+ protected AbstractTestSuite(final ProviderTestConfig providerConfig,
+ final String prefix,
+ final boolean nested,
+ final boolean addEmptyDir)
+ throws Exception
+ {
+ super(new TestSuite());
+ testSuite = (TestSuite) fTest;
+ this.providerConfig = providerConfig;
+ this.prefix = prefix;
+ this.addEmptyDir = addEmptyDir;
+ addBaseTests();
+ if (!nested)
+ {
+ // Add nested tests
+ // TODO - move nested jar and zip tests here
+ // TODO - enable this again
+ //testSuite.addTest( new ProviderTestSuite( new JunctionProviderConfig( providerConfig ), "junction.", true ));
+ }
+ }
+
+ /**
+ * Adds base tests - excludes the nested test cases.
+ */
+ protected void addBaseTests() throws Exception
+ {
+ }
+
+ /**
+ * Adds the tests from a class to this suite. The supplied class must be
+ * a subclass of {@link AbstractProviderTestCase} and have a public a
+ * no-args constructor. This method creates an instance of the supplied
+ * class for each public 'testNnnn' method provided by the class.
+ */
+ public void addTests(final Class<?> testClass) throws Exception
+ {
+ // Verify the class
+ if (!AbstractProviderTestCase.class.isAssignableFrom(testClass))
+ {
+ throw new Exception("Test class " + testClass.getName() + " is not assignable to " + AbstractProviderTestCase.class.getName());
+ }
+
+ // Locate the test methods
+ final Method[] methods = testClass.getMethods();
+ for (final Method method2 : methods)
+ {
+ final Method method = method2;
+ if (!method.getName().startsWith("test")
+ || Modifier.isStatic(method.getModifiers())
+ || method.getReturnType() != Void.TYPE
+ || method.getParameterTypes().length != 0)
+ {
+ continue;
+ }
+
+ // Create instance
+ final AbstractProviderTestCase testCase = (AbstractProviderTestCase) testClass.newInstance();
+ testCase.setMethod(method);
+ testCase.setName(prefix + method.getName());
+ testCase.addEmptyDir(this.addEmptyDir);
+ testSuite.addTest(testCase);
+ }
+ }
+
+ @Override
+ public void run(final TestResult result) {
+ final Protectable p = new Protectable() {
+ @Override
+ public void protect() throws Exception {
+ setUp();
+ basicRun(result);
+ tearDown();
+ validateThreadSnapshot();
+ }
+ };
+ result.runProtected(this, p);
+ }
+
+ @Override
+ protected void setUp() throws Exception
+ {
+ startThreadSnapshot = createThreadSnapshot();
+
+ // Locate the temp directory, and clean it up
+ tempDir = AbstractVfsTestCase.getTestDirectory("temp");
+ FileUtils.cleanDirectory(tempDir);
+ checkTempDir("Temp dir not empty before test");
+
+ // Create the file system manager
+ manager = providerConfig.getDefaultFileSystemManager();
+ manager.setFilesCache(providerConfig.getFilesCache());
+
+ final DefaultFileReplicator replicator = new DefaultFileReplicator(tempDir);
+ manager.setReplicator(new PrivilegedFileReplicator(replicator));
+ manager.setTemporaryFileStore(replicator);
+
+ providerConfig.prepare(manager);
+
+ if (!manager.hasProvider("file"))
+ {
+ manager.addProvider("file", new DefaultLocalFileProvider());
+ }
+
+ manager.init();
+
+ // Locate the base folders
+ baseFolder = providerConfig.getBaseTestFolder(manager);
+ readFolder = baseFolder.resolveFile("read-tests");
+ writeFolder = baseFolder.resolveFile("write-tests");
+
+ // Make some assumptions about the read folder
+ assertTrue("Folder does not exist: " + readFolder, readFolder.exists());
+ assertFalse(readFolder.getName().getPath().equals(FileName.ROOT_PATH));
+
+ // Configure the tests
+ final Enumeration<Test> tests = testSuite.tests();
+ while (tests.hasMoreElements())
+ {
+ final Test test = tests.nextElement();
+ if (test instanceof AbstractProviderTestCase)
+ {
+ final AbstractProviderTestCase providerTestCase = (AbstractProviderTestCase) test;
+ providerTestCase.setConfig(manager, providerConfig, baseFolder, readFolder, writeFolder);
+ }
+ }
+ }
+
+ @Override
+ protected void tearDown() throws Exception
+ {
+ readFolder.close();
+ writeFolder.close();
+ baseFolder.close();
+
+ readFolder = null;
+ writeFolder = null;
+ baseFolder = null;
+ testSuite = null;
+
+ // force the SoftRefFilesChache to free all files
+ System.gc();
+ Thread.sleep(1000);
+ System.gc();
+ Thread.sleep(1000);
+ System.gc();
+ Thread.sleep(1000);
+ System.gc();
+ Thread.sleep(1000);
+
+ manager.freeUnusedResources();
+ manager.close();
+
+ // Make sure temp directory is empty or gone
+ checkTempDir("Temp dir not empty after test");
+ }
+
+ private void validateThreadSnapshot()
+ {
+ endThreadSnapshot = createThreadSnapshot();
+
+ final Thread[] diffThreadSnapshot = diffThreadSnapshot(startThreadSnapshot, endThreadSnapshot);
+ if (diffThreadSnapshot.length > 0)
+ {
+ final String message = dumpThreadSnapshot(diffThreadSnapshot);
+ /*
+ if (providerConfig.checkCleanThreadState())
+ {
+ // close the manager to do a "not thread safe" release of all resources
+ // and allow the vm to shutdown
+ manager.close();
+ fail(message);
+ }
+ else
+ {
+ */
+ System.out.println(message);
+ // }
+ }
+ // System.in.read();
+ }
+
+ /**
+ * Asserts that the temp dir is empty or gone.
+ */
+ private void checkTempDir(final String assertMsg)
+ {
+ if (tempDir.exists())
+ {
+ assertTrue(assertMsg + " (" + tempDir.getAbsolutePath() + ")", tempDir.isDirectory() && tempDir.list().length == 0);
+ }
+ }
+
+ private String dumpThreadSnapshot(final Thread[] threadSnapshot)
+ {
+ final StringBuffer sb = new StringBuffer(256);
+ sb.append("created threads still running:\n");
+
+ Field threadTargetField = null;
+ try
+ {
+ threadTargetField = Thread.class.getDeclaredField("target");
+ threadTargetField.setAccessible(true);
+ }
+ catch (final NoSuchFieldException e)
+ {
+ // ignored
+ }
+
+ for (int iter = 0; iter < threadSnapshot.length; iter++)
+ {
+ final Thread thread = threadSnapshot[iter];
+ if (thread == null || !thread.isAlive())
+ {
+ continue;
+ }
+
+ sb.append("#");
+ sb.append(iter + 1);
+ sb.append(": ");
+ sb.append(thread.getThreadGroup() != null ?
+ thread.getThreadGroup().getName() : "(null)");
+ sb.append("\t");
+ sb.append(thread.getName());
+ sb.append("\t");
+ sb.append(thread.getState());
+ sb.append("\t");
+ if (thread.isDaemon())
+ {
+ sb.append("daemon");
+ }
+ else
+ {
+ sb.append("not_a_daemon");
+ }
+
+ if (threadTargetField != null)
+ {
+ sb.append("\t");
+ try
+ {
+ final Object threadTarget = threadTargetField.get(thread);
+ if (threadTarget != null)
+ {
+ sb.append(threadTarget.getClass());
+ }
+ else
+ {
+ sb.append("null");
+ }
+ }
+ catch (final IllegalAccessException e)
+ {
+ sb.append("unknown class");
+ }
+ }
+
+ sb.append("\n");
+ }
+
+ return sb.toString();
+ }
+
+ private Thread[] diffThreadSnapshot(final Thread[] startThreadSnapshot, final Thread[] endThreadSnapshot)
+ {
+ final List<Thread> diff = new ArrayList<Thread>(10);
+
+ nextEnd: for (int iterEnd = 0; iterEnd < endThreadSnapshot.length; iterEnd++)
+ {
+ for (int iterStart = 0; iterStart < startThreadSnapshot.length; iterStart++)
+ {
+ if (startThreadSnapshot[iterStart] == endThreadSnapshot[iterEnd])
+ {
+ continue nextEnd;
+ }
+ }
+
+ diff.add(endThreadSnapshot[iterEnd]);
+ }
+
+ final Thread ret[] = new Thread[diff.size()];
+ diff.toArray(ret);
+ return ret;
+ }
+
+ 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/trunk/core/src/test/java/org/apache/commons/vfs2/test/CacheTestSuite.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/CacheTestSuite.java
new file mode 100644
index 0000000..d9c6c06
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/CacheTestSuite.java
@@ -0,0 +1,38 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+
+/**
+ * The suite of tests for a file cache.
+ */
+public class CacheTestSuite
+ extends AbstractTestSuite
+{
+ public CacheTestSuite(final ProviderTestConfig providerConfig) throws Exception
+ {
+ this(providerConfig, "", false);
+ }
+
+ protected CacheTestSuite(final ProviderTestConfig providerConfig,
+ final String prefix,
+ final boolean nested)
+ throws Exception
+ {
+ super(providerConfig, prefix, nested);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/test/ContentTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ContentTests.java
new file mode 100644
index 0000000..e757a57
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ContentTests.java
@@ -0,0 +1,383 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import java.io.InputStream;
+
+import org.apache.commons.vfs2.FileContent;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.NameScope;
+
+/**
+ * Test cases for reading file content.
+ */
+public class ContentTests
+ extends AbstractProviderTestCase
+{
+ /**
+ * Asserts that every expected file exists, and has the expected content.
+ */
+ 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
+ {
+ for (final FileInfo fileInfo : expected.children.values())
+ {
+ final FileObject child = folder.resolveFile(fileInfo.baseName, NameScope.CHILD);
+
+ assertTrue(child.getName().toString(), child.exists());
+ if (fileInfo.type == FileType.FILE)
+ {
+ assertSameContent(fileInfo.content, child);
+ }
+ else
+ {
+ assertSameContent(fileInfo, child);
+ }
+ }
+ }
+
+ /**
+ * Tests existence determination.
+ */
+ public void testExists() throws Exception
+ {
+ // Test a file
+ FileObject file = getReadFolder().resolveFile("file1.txt");
+ assertTrue("file exists", file.exists());
+ assertTrue("file exists", file.getType() != FileType.IMAGINARY);
+
+ // Test a folder
+ file = getReadFolder().resolveFile("dir1");
+ assertTrue("folder exists", file.exists());
+ assertTrue("folder exists", file.getType() != FileType.IMAGINARY);
+
+ // Test an unknown file
+ file = getReadFolder().resolveFile("unknown-child");
+ assertTrue("unknown file does not exist", !file.exists());
+ assertTrue("unknown file does not exist",
+ file.getType() == FileType.IMAGINARY);
+
+ // Test an unknown file in an unknown folder
+ file = getReadFolder().resolveFile("unknown-folder/unknown-child");
+ assertTrue("unknown file does not exist", !file.exists());
+ assertTrue("unknown file does not exist",
+ file.getType() == FileType.IMAGINARY);
+ }
+
+ /**
+ * Tests attributes
+ */
+ public void testAttributes() throws FileSystemException {
+ this.getReadFolder().getContent().getAttributes();
+ }
+
+ /**
+ * Tests root of file system exists.
+ */
+ 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.
+ */
+ public void testRootAPI() throws FileSystemException
+ {
+ if (!this.getProviderConfig().isFileSystemRootAccessible())
+ {
+ return;
+ }
+ testRoot(getFileSystem().getRoot());
+ }
+
+ private void testRoot(final FileObject root) throws FileSystemException
+ {
+ assertTrue(root.exists());
+ assertTrue(root.getType() != FileType.IMAGINARY);
+ }
+
+ /**
+ * Tests parent identity
+ */
+ 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());
+ assertTrue("child does not exist", !child.exists());
+ assertSame(folder, child.getParent());
+
+ // Test when neither exists
+ folder = getReadFolder().resolveFile("unknown-folder");
+ child = folder.resolveFile("unknown-file");
+ assertTrue("folder does not exist", !folder.exists());
+ assertTrue("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 children cannot be listed for non-folders.
+ */
+ public void testChildren() throws FileSystemException
+ {
+ // Check for file
+ FileObject file = getReadFolder().resolveFile("file1.txt");
+ assertSame(FileType.FILE, file.getType());
+ assertTrue(file.isFile());
+ try
+ {
+ file.getChildren();
+ fail();
+ }
+ catch (final FileSystemException e)
+ {
+ assertSameMessage("vfs.provider/list-children-not-folder.error", file, e);
+ }
+
+ // Should be able to get child by name
+ file = file.resolveFile("some-child");
+ assertNotNull(file);
+
+ // Check for unknown file
+ file = getReadFolder().resolveFile("unknown-file");
+ assertTrue(!file.exists());
+ try
+ {
+ file.getChildren();
+ fail();
+ }
+ catch (final FileSystemException e)
+ {
+ assertSameMessage("vfs.provider/list-children-not-folder.error", file, e);
+ }
+
+ // Should be able to get child by name
+ final FileObject child = file.resolveFile("some-child");
+ assertNotNull(child);
+ }
+
+ /**
+ * Tests content.
+ */
+ public void testContent() throws Exception
+ {
+ // Test non-empty file
+ FileObject file = getReadFolder().resolveFile("file1.txt");
+ assertSameContent(FILE1_CONTENT, file);
+
+ // Test empty file
+ file = getReadFolder().resolveFile("empty.txt");
+ assertSameContent("", file);
+ }
+
+ /**
+ * Tests that unknown files have no content.
+ */
+ 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.
+ */
+ public void testReadSingleSequencial() throws Exception
+ {
+ final FileObject file = getReadFolder().resolveFile("file1.txt");
+ assertTrue(file.exists());
+
+ file.getContent().getInputStream().close();
+ file.getContent().getInputStream().close();
+ }
+
+ /**
+ * Tests concurrent reads on a file.
+ */
+ public void testReadSingleConcurrent() throws Exception
+ {
+ final FileObject file = getReadFolder().resolveFile("file1.txt");
+ assertTrue(file.exists());
+
+ // Start reading from the file
+ final InputStream instr = file.getContent().getInputStream();
+ try
+ {
+ // Start reading again
+ file.getContent().getInputStream().close();
+ }
+ finally
+ {
+ instr.close();
+ }
+ }
+
+ /**
+ * Tests concurrent reads on different files works.
+ */
+ 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());
+
+ // Start reading from the file
+ final InputStream instr = file.getContent().getInputStream();
+ try
+ {
+ // Try to read from other file
+ assertSameContent("", emptyFile);
+ }
+ finally
+ {
+ instr.close();
+ }
+ }
+
+ /**
+ * Tests that content and file objects are usable after being closed.
+ */
+ public void testReuse() 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();
+
+ // Read the content again
+ assertSameContent(FILE1_CONTENT, file);
+ }
+
+ /**
+ * Tests that input streams are cleaned up on file close.
+ */
+ public void testInputStreamMultipleCleanup() throws Exception
+ {
+ // Get the test file
+ final FileObject file = getReadFolder().resolveFile("file1.txt");
+ assertEquals(FileType.FILE, file.getType());
+ assertTrue(file.isFile());
+
+ // Open some input streams
+ final InputStream instr1 = file.getContent().getInputStream();
+ assertTrue(instr1.read() == FILE1_CONTENT.charAt(0));
+ final InputStream instr2 = file.getContent().getInputStream();
+ assertTrue(instr2.read() == FILE1_CONTENT.charAt(0));
+
+ // Close the file
+ file.close();
+
+ // Check
+ assertTrue(instr1.read() == -1);
+ assertTrue(instr2.read() == -1);
+ }
+
+ /**
+ * Tests that input streams are cleaned up on file close.
+ */
+ public void testInputStreamSingleCleanup() throws Exception
+ {
+ // Get the test file
+ final FileObject file = getReadFolder().resolveFile("file1.txt");
+ assertEquals(FileType.FILE, file.getType());
+ assertTrue(file.isFile());
+
+ // Open some input streams
+ final InputStream instr1 = file.getContent().getInputStream();
+ assertTrue(instr1.read() == FILE1_CONTENT.charAt(0));
+
+ // Close the file
+ file.close();
+
+ // Check
+ assertTrue(instr1.read() == -1);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/test/FileInfo.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/FileInfo.java
new file mode 100644
index 0000000..ad35a2d
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/FileInfo.java
@@ -0,0 +1,82 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import org.apache.commons.vfs2.FileType;
+
+/**
+ * Info about a file.
+ */
+class FileInfo
+{
+ String baseName;
+ FileType type;
+ String content;
+ Map<String, FileInfo> children = new HashMap<String, FileInfo>();
+ FileInfo parent;
+
+ public FileInfo(final String name, final FileType type)
+ {
+ baseName = name;
+ this.type = type;
+ this.content = null;
+ }
+
+ public FileInfo(final String name, final FileType type, final String content)
+ {
+ baseName = name;
+ this.type = type;
+ this.content = content;
+ }
+
+ public FileInfo getParent()
+ {
+ return parent;
+ }
+
+ /**
+ * Adds a child.
+ */
+ public void addChild(final FileInfo child)
+ {
+ children.put(child.baseName, child);
+ child.parent = this;
+ }
+
+ /**
+ * Adds a child file.
+ */
+ public FileInfo addFile(final String baseName, final String content)
+ {
+ final FileInfo child = new FileInfo(baseName, FileType.FILE, content);
+ addChild(child);
+ return child;
+ }
+
+ /**
+ * Adds a child folder.
+ */
+ public FileInfo addFolder(final String baseName)
+ {
+ final FileInfo child = new FileInfo(baseName, FileType.FOLDER, null);
+ addChild(child);
+ return child;
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/test/FileSystemManagerFactoryTestCase.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/FileSystemManagerFactoryTestCase.java
new file mode 100644
index 0000000..2429663
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/FileSystemManagerFactoryTestCase.java
@@ -0,0 +1,70 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import java.io.File;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.VFS;
+
+/**
+ * Test cases for the VFS factory.
+ */
+public class FileSystemManagerFactoryTestCase
+ extends AbstractVfsTestCase
+{
+ /**
+ * Sanity test.
+ */
+ public void testDefaultInstance() throws Exception
+ {
+ // Locate the default manager
+ final FileSystemManager manager = VFS.getManager();
+
+ // Lookup a test jar file
+ final File jarFile = getTestResource("test.jar");
+ // File
+ final FileObject file = manager.toFileObject(jarFile);
+ check(manager, file);
+ // URI
+ final FileObject file2 = manager.resolveFile(jarFile.toURI());
+ check(manager, file2);
+ // URL
+ final FileObject file3 = manager.resolveFile(jarFile.toURI().toURL());
+ 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/trunk/core/src/test/java/org/apache/commons/vfs2/test/LastModifiedTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/LastModifiedTests.java
new file mode 100644
index 0000000..5b42101
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/LastModifiedTests.java
@@ -0,0 +1,127 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import static org.junit.Assert.assertNotEquals;
+
+import java.util.Date;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.junit.Assert;
+
+/**
+ * Test cases for getting and setting file last modified time.
+ */
+public class LastModifiedTests extends AbstractProviderTestCase
+{
+ private void assertDelta(final String message, final long expected, final long actual, final long delta)
+ {
+ if (expected == actual)
+ {
+ return;
+ }
+ if (Math.abs(expected - actual) > Math.max(delta, 1000)) // getLastModTimeAccuracy() is not accurate
+ {
+ Assert.fail(String.format("%s expected=%d (%s), actual=%d (%s), delta=%d", message, Long.valueOf(expected), new Date(expected).toString(), Long.valueOf(actual), new Date(actual).toString(), Long.valueOf(delta)));
+ }
+ }
+
+ /**
+ * Returns the capabilities required by the tests of this test case.
+ */
+ @Override
+ protected Capability[] getRequiredCaps()
+ {
+ return new Capability[]
+ { Capability.GET_LAST_MODIFIED };
+ }
+
+ /**
+ * Tests FileSystem#getLastModTimeAccuracy for sane values.
+ * @throws FileSystemException if error occurred
+ */
+ public void testGetAccurary() throws FileSystemException
+ {
+ final FileObject file = getReadFolder().resolveFile("file1.txt");
+ final long lastModTimeAccuracy = (long)file.getFileSystem().getLastModTimeAccuracy();
+ // System.out.println("Accuracy on " + file.getFileSystem().getRootURI() + " is " + lastModTimeAccuracy + " as told by " + file.getFileSystem().getClass().getCanonicalName());
+ assertTrue("Accuracy must be positive", lastModTimeAccuracy >= 0);
+ assertTrue("Accuracy must be < 2m", lastModTimeAccuracy < 2 * 60 * 1000); // just any sane limit
+ }
+
+ /**
+ * Tests getting the last modified time of a folder.
+ * @throws FileSystemException if error occurred
+ */
+ public void testGetLastModifiedFolder() throws FileSystemException
+ {
+ final FileObject file = getReadFolder().resolveFile("dir1");
+ assertNotEquals(0L, file.getContent().getLastModifiedTime());
+ }
+
+ /**
+ * Tests getting the last modified time of a file.
+ * @throws FileSystemException if error occurred
+ */
+ public void testGetLastModifiedFile() throws FileSystemException
+ {
+ final FileObject file = getReadFolder().resolveFile("file1.txt");
+ assertNotEquals(0L, file.getContent().getLastModifiedTime());
+ }
+
+ /**
+ * Tests setting the last modified time of a folder.
+ * @throws FileSystemException if error occurred
+ */
+ public void testSetLastModifiedFolder() throws FileSystemException
+ {
+ final long yesterday = System.currentTimeMillis() - 24*60*60*1000;
+
+ if (getReadFolder().getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FOLDER))
+ {
+ // Try a folder
+ final FileObject folder = getReadFolder().resolveFile("dir1");
+ folder.getContent().setLastModifiedTime(yesterday);
+ final long lastModTimeAccuracy = (long)folder.getFileSystem().getLastModTimeAccuracy();
+ // folder.refresh(); TODO: does not work with SSH VFS-563
+ final long lastModifiedTime = folder.getContent().getLastModifiedTime();
+ assertDelta("set/getLastModified on Folder", yesterday, lastModifiedTime, lastModTimeAccuracy);
+ }
+ }
+
+ /**
+ * Tests setting the last modified time of file.
+ * @throws FileSystemException if error occurred
+ */
+ public void testSetLastModifiedFile() throws FileSystemException
+ {
+ final long yesterday = System.currentTimeMillis() - 24*60*60*1000;
+
+ if (getReadFolder().getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FILE))
+ {
+ // Try a file
+ final FileObject file = getReadFolder().resolveFile("file1.txt");
+ file.getContent().setLastModifiedTime(yesterday);
+ final long lastModTimeAccuracy = (long)file.getFileSystem().getLastModTimeAccuracy();
+ // folder.refresh(); TODO: does not work with SSH VFS-563
+ final long lastModifiedTime = file.getContent().getLastModifiedTime();
+ assertDelta("set/getLastModified on File", yesterday, lastModifiedTime, lastModTimeAccuracy);
+ }
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/test/NamingTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/NamingTests.java
new file mode 100644
index 0000000..9d90d45
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/NamingTests.java
@@ -0,0 +1,459 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.NameScope;
+
+/**
+ * Test cases for file naming.
+ * <p>
+ * TODO - Add tests for all FileName methods.
+ */
+public class NamingTests
+ extends AbstractProviderTestCase
+{
+ /**
+ * Tests resolution of relative file names via the FS manager
+ */
+ 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.
+ */
+ 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 behaviour 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
+ try
+ {
+ getManager().resolveFile("%q");
+ fail();
+ }
+ catch (final FileSystemException e)
+ {
+ }
+
+ // free basefile
+ getManager().setBaseFile((FileObject) null);
+ }
+
+ /**
+ * Tests the root file name.
+ */
+ 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());
+ }
+
+ /**
+ * Tests child file names.
+ */
+ 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);
+ }
+
+ /**
+ * Name resolution tests that are common for CHILD or DESCENDENT scope.
+ */
+ private void checkDescendentNames(final FileName name,
+ final NameScope scope)
+ throws Exception
+ {
+ // Make some assumptions about the name
+ assertTrue(!name.getPath().equals("/"));
+ assertTrue(!name.getPath().endsWith("/a"));
+ assertTrue(!name.getPath().endsWith("/a/b"));
+
+ // Test names with the same prefix
+ final String path = name.getPath() + "/a";
+ assertSameName(path, name, path, scope);
+ assertSameName(path, name, "../" + name.getBaseName() + "/a", scope);
+
+ // Test an empty name
+ assertBadName(name, "", scope);
+
+ // Test . name
+ assertBadName(name, ".", scope);
+ assertBadName(name, "./", scope);
+
+ // Test ancestor names
+ assertBadName(name, "..", scope);
+ assertBadName(name, "../a", scope);
+ assertBadName(name, "../" + name.getBaseName() + "a", scope);
+ assertBadName(name, "a/..", scope);
+
+ // Test absolute names
+ assertBadName(name, "/", scope);
+ assertBadName(name, "/a", scope);
+ assertBadName(name, "/a/b", scope);
+ assertBadName(name, name.getPath(), scope);
+ assertBadName(name, name.getPath() + "a", scope);
+ }
+
+ /**
+ * Checks that a relative name resolves to the expected absolute path.
+ * Tests both forward and back slashes.
+ */
+ 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());
+
+ String temp;
+
+ // Replace the separators
+ temp = relName.replace('\\', '/');
+ name = getManager().resolveName(baseName, temp, scope);
+ assertEquals(expectedPath, name.getPath());
+
+ // And again
+ temp = relName.replace('/', '\\');
+ name = getManager().resolveName(baseName, temp, scope);
+ assertEquals(expectedPath, name.getPath());
+ }
+
+ /**
+ * Checks that a relative name resolves to the expected absolute path.
+ * Tests both forward and back slashes.
+ */
+ private void assertSameName(final String expectedPath,
+ final FileName baseName,
+ final String relName) throws Exception
+ {
+ assertSameName(expectedPath, baseName, relName, NameScope.FILE_SYSTEM);
+ }
+
+ /**
+ * Tests relative name resolution, relative to the base folder.
+ */
+ public void testNameResolution() throws Exception
+ {
+ final FileName baseName = getReadFolder().getName();
+ final String parentPath = baseName.getParent().getPath();
+ final String path = baseName.getPath();
+ final String childPath = path + "/some-child";
+
+ // Test empty relative path
+ assertSameName(path, baseName, "");
+
+ // Test . relative path
+ assertSameName(path, baseName, ".");
+
+ // Test ./ relative path
+ assertSameName(path, baseName, "./");
+
+ // Test .// relative path
+ assertSameName(path, baseName, ".//");
+
+ // Test .///.///. relative path
+ assertSameName(path, baseName, ".///.///.");
+ assertSameName(path, baseName, "./\\/.\\//.");
+
+ // Test <elem>/.. relative path
+ assertSameName(path, baseName, "a/..");
+
+ // Test .. relative path
+ assertSameName(parentPath, baseName, "..");
+
+ // Test ../ relative path
+ assertSameName(parentPath, baseName, "../");
+
+ // Test ..//./ relative path
+ assertSameName(parentPath, baseName, "..//./");
+ assertSameName(parentPath, baseName, "..//.\\");
+
+ // Test <elem>/../.. relative path
+ assertSameName(parentPath, baseName, "a/../..");
+
+ // Test <elem> relative path
+ assertSameName(childPath, baseName, "some-child");
+
+ // Test ./<elem> relative path
+ assertSameName(childPath, baseName, "./some-child");
+
+ // Test ./<elem>/ relative path
+ assertSameName(childPath, baseName, "./some-child/");
+
+ // Test <elem>/././././ relative path
+ assertSameName(childPath, baseName, "./some-child/././././");
+
+ // Test <elem>/../<elem> relative path
+ assertSameName(childPath, baseName, "a/../some-child");
+
+ // Test <elem>/<elem>/../../<elem> relative path
+ assertSameName(childPath, baseName, "a/b/../../some-child");
+ }
+
+ /**
+ * Tests descendent name resolution.
+ */
+ 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);
+ }
+
+ /**
+ * Tests resolution of absolute names.
+ */
+ 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 resolution of absolute names.
+ */
+ private void checkAbsoluteNames(final FileName name) throws Exception
+ {
+ // Root
+ assertSameName("/", name, "/");
+ assertSameName("/", name, "//");
+ assertSameName("/", name, "/.");
+ assertSameName("/", name, "/some file/..");
+
+ // Some absolute names
+ assertSameName("/a", name, "/a");
+ assertSameName("/a", name, "/./a");
+ assertSameName("/a", name, "/a/.");
+ assertSameName("/a/b", name, "/a/b");
+
+ // Some bad names
+ assertBadName(name, "/..", NameScope.FILE_SYSTEM);
+ assertBadName(name, "/a/../..", NameScope.FILE_SYSTEM);
+ }
+
+ /**
+ * Asserts that a particular relative name is invalid for a particular
+ * scope.
+ */
+ private void assertBadName(final FileName name,
+ final String relName,
+ final NameScope scope)
+ {
+ try
+ {
+ getManager().resolveName(name, relName, scope);
+ fail("expected failure");
+ }
+ catch (final FileSystemException e)
+ {
+ // TODO - should check error message
+ }
+ }
+
+ /**
+ * Tests conversion from absolute to relative names.
+ */
+ 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());
+
+ // Try child and descendent names (against root)
+ testRelName(name, "child");
+ testRelName(name, "child1/child2");
+
+ // Try own name (against root)
+ testRelName(name, ".");
+ }
+
+ /**
+ * Checks that a file name converts to an expected relative path
+ */
+ private void testRelName(final FileName baseName,
+ final String relPath)
+ throws Exception
+ {
+ final FileName expectedName = getManager().resolveName(baseName, relPath);
+
+ // Convert to relative path, and check
+ final String actualRelPath = baseName.getRelativeName(expectedName);
+ assertEquals(relPath, actualRelPath);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/test/PermissionsTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/PermissionsTests.java
new file mode 100644
index 0000000..7b6be31
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/PermissionsTests.java
@@ -0,0 +1,186 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import java.io.OutputStream;
+
+import org.junit.Assert;
+import org.apache.commons.lang3.SystemUtils;
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.Selectors;
+import org.apache.commons.vfs2.provider.local.LocalFileSystem;
+
+/**
+ * Additional file permission tests.
+ *
+ * Used by Local and SFTP File System.
+ *
+ * @since 2.1
+ */
+public class PermissionsTests extends AbstractProviderTestCase
+{
+ public static final String FILENAME = "permission.txt";
+
+ /**
+ * Returns the capabilities required by the tests of this test case.
+ */
+ @Override
+ protected Capability[] getRequiredCaps()
+ {
+ return new Capability[]
+ {
+ Capability.CREATE,
+ Capability.DELETE,
+ Capability.READ_CONTENT,
+ Capability.WRITE_CONTENT,
+ };
+ }
+
+ /**
+ * Tests for the execution permission.
+ */
+ public void testExecutable() throws Exception
+ {
+ final FileObject file = createTestFile();
+
+ // On Windows, all files are executable
+ if (isWindows())
+ {
+ Assert.assertTrue(file.isExecutable());
+
+ } else
+ {
+ // Set the executable flag for owner
+ file.setExecutable(true, true);
+ Assert.assertTrue(file.isExecutable());
+
+ // Set the executable flag for all
+ file.setExecutable(true, false);
+ Assert.assertTrue(file.isExecutable());
+
+ // Clear the executable flag
+ file.setExecutable(false, true);
+ Assert.assertFalse(file.isExecutable());
+ }
+ }
+
+
+ /**
+ * Tests for the writeable permission
+ */
+ public void testWriteable() throws Exception
+ {
+ final FileObject file = createTestFile();
+
+ // Set the write permission for owner
+ file.setWritable(true, true);
+ Assert.assertTrue(file.isWriteable());
+
+ // Set the write permission for all
+ file.setWritable(true, false);
+ Assert.assertTrue(file.isWriteable());
+
+ // Clear the write permission
+ file.setWritable(false, true);
+ Assert.assertFalse(file.isWriteable());
+ }
+
+
+ /**
+ * Tests for the readable permission
+ */
+ public void testReadable() throws Exception
+ {
+ final FileObject file = createTestFile();
+
+ if (isWindows())
+ {
+ // On Windows, all owned files are readable
+ Assert.assertTrue(file.isReadable());
+ }
+ else
+ {
+ // Set the readable permission for owner
+ file.setReadable(true, true);
+ Assert.assertTrue(file.isReadable());
+
+ // Set the readable permission for all
+ file.setReadable(true, false);
+ Assert.assertTrue(file.isReadable());
+
+ // Clear the readable permission
+ file.setReadable(false, true);
+ Assert.assertFalse(file.isReadable());
+ }
+ }
+
+
+ /**
+ * 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();
+ }
+
+
+ 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);
+ assertTrue(!file.exists());
+
+ // Create the source file
+ final String content = "Here is some sample content for the file. Blah Blah Blah.";
+
+ final OutputStream os = file.getContent().getOutputStream();
+ try
+ {
+ os.write(content.getBytes("utf-8"));
+ }
+ finally
+ {
+ os.close();
+ }
+ return file;
+ }
+
+
+ /**
+ * Returns true if the filesystem is a LocalFileSystem on Windows
+ */
+ private boolean isWindows()
+ {
+ return SystemUtils.IS_OS_WINDOWS && this.getFileSystem() instanceof LocalFileSystem;
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderCacheStrategyTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderCacheStrategyTests.java
new file mode 100644
index 0000000..a2736fd
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderCacheStrategyTests.java
@@ -0,0 +1,172 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import org.apache.commons.vfs2.CacheStrategy;
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.Selectors;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.impl.VirtualFileSystem;
+import org.apache.commons.vfs2.provider.ram.RamFileObject;
+import org.apache.commons.vfs2.util.FileObjectUtils;
+
+/**
+ * Test the cache stragey
+ */
+public class ProviderCacheStrategyTests
+ extends AbstractProviderTestCase
+{
+ /**
+ * Returns the capabilities required by the tests of this test case.
+ */
+ @Override
+ protected Capability[] getRequiredCaps()
+ {
+ return new Capability[]
+ {
+ Capability.CREATE,
+ Capability.GET_TYPE,
+ Capability.LIST_CHILDREN,
+ };
+ }
+
+ /**
+ * Test the manual cache strategy
+ */
+ public void testManualCache() throws Exception
+ {
+ final FileObject scratchFolder = getWriteFolder();
+ if (FileObjectUtils.isInstanceOf(getBaseFolder(), RamFileObject.class) ||
+ scratchFolder.getFileSystem() instanceof VirtualFileSystem)
+ {
+ // cant check ram filesystem as every manager holds its own ram filesystem data
+ return;
+ }
+
+ scratchFolder.delete(Selectors.EXCLUDE_SELF);
+
+ final DefaultFileSystemManager fs = createManager();
+ fs.setCacheStrategy(CacheStrategy.MANUAL);
+ fs.init();
+ final FileObject foBase2 = getBaseTestFolder(fs);
+
+ final FileObject cachedFolder = foBase2.resolveFile(scratchFolder.getName().getPath());
+
+ FileObject[] fos = cachedFolder.getChildren();
+ assertContainsNot(fos, "file1.txt");
+
+ scratchFolder.resolveFile("file1.txt").createFile();
+
+ fos = cachedFolder.getChildren();
+ assertContainsNot(fos, "file1.txt");
+
+ cachedFolder.refresh();
+ fos = cachedFolder.getChildren();
+ assertContains(fos, "file1.txt");
+ }
+
+ /**
+ * Test the on_resolve strategy
+ */
+ public void testOnResolveCache() throws Exception
+ {
+ final FileObject scratchFolder = getWriteFolder();
+ if (FileObjectUtils.isInstanceOf(getBaseFolder(), RamFileObject.class) ||
+ scratchFolder.getFileSystem() instanceof VirtualFileSystem)
+ {
+ // cant check ram filesystem as every manager holds its own ram filesystem data
+ return;
+ }
+
+ scratchFolder.delete(Selectors.EXCLUDE_SELF);
+
+ final DefaultFileSystemManager fs = createManager();
+ fs.setCacheStrategy(CacheStrategy.ON_RESOLVE);
+ fs.init();
+ final FileObject foBase2 = getBaseTestFolder(fs);
+
+ FileObject cachedFolder = foBase2.resolveFile(scratchFolder.getName().getPath());
+
+ FileObject[] fos = cachedFolder.getChildren();
+ assertContainsNot(fos, "file1.txt");
+
+ 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
+ */
+ public void testOnCallCache() throws Exception
+ {
+ final FileObject scratchFolder = getWriteFolder();
+ if (FileObjectUtils.isInstanceOf(getBaseFolder(), RamFileObject.class) ||
+ scratchFolder.getFileSystem() instanceof VirtualFileSystem)
+ {
+ // cant check ram filesystem as every manager holds its own ram filesystem data
+ return;
+ }
+
+ scratchFolder.delete(Selectors.EXCLUDE_SELF);
+
+ final DefaultFileSystemManager fs = createManager();
+ fs.setCacheStrategy(CacheStrategy.ON_CALL);
+ fs.init();
+ final FileObject foBase2 = getBaseTestFolder(fs);
+
+ final FileObject cachedFolder = foBase2.resolveFile(scratchFolder.getName().getPath());
+
+ FileObject[] fos = cachedFolder.getChildren();
+ assertContainsNot(fos, "file1.txt");
+
+ 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;
+ }
+ }
+
+ fail(string + " should be seen");
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderDeleteTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderDeleteTests.java
new file mode 100644
index 0000000..ef12b4e
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderDeleteTests.java
@@ -0,0 +1,146 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSelectInfo;
+import org.apache.commons.vfs2.FileSelector;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.FileTypeSelector;
+import org.apache.commons.vfs2.Selectors;
+
+/**
+ * File system test that do some delete operations.
+ */
+public class ProviderDeleteTests
+ extends AbstractProviderTestCase
+{
+ private class FileNameSelector implements FileSelector
+ {
+ final String basename;
+
+ private FileNameSelector(final String basename)
+ {
+ this.basename = basename;
+ }
+
+ @Override
+ public boolean includeFile(final FileSelectInfo fileInfo) throws Exception
+ {
+ return this.basename.equals(fileInfo.getFile().getName().getBaseName());
+ }
+
+ @Override
+ public boolean traverseDescendents(final FileSelectInfo fileInfo) throws Exception
+ {
+ return true;
+ }
+ }
+
+ /**
+ * Returns the capabilities required by the tests of this test case.
+ */
+ @Override
+ protected Capability[] getRequiredCaps()
+ {
+ 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
+ {
+ final FileObject scratchFolder = getWriteFolder();
+
+ // Make sure the test folder is empty
+ scratchFolder.delete(Selectors.EXCLUDE_SELF);
+ scratchFolder.createFolder();
+
+ final FileObject dir1 = scratchFolder.resolveFile("dir1");
+ dir1.createFolder();
+ final FileObject dir1file1 = dir1.resolveFile("a.txt");
+ dir1file1.createFile();
+ final FileObject dir2 = scratchFolder.resolveFile("dir2");
+ dir2.createFolder();
+ final FileObject dir2file1 = dir2.resolveFile("b.txt");
+ dir2file1.createFile();
+
+ return scratchFolder;
+ }
+
+ /**
+ * deletes the complete structure
+ */
+ public void testDeleteFiles() throws Exception
+ {
+ final FileObject scratchFolder = createScratchFolder();
+
+ assertEquals(scratchFolder.delete(Selectors.EXCLUDE_SELF), 4);
+ }
+
+ /**
+ * deletes a single file
+ */
+ public void testDeleteFile() throws Exception
+ {
+ final FileObject scratchFolder = createScratchFolder();
+
+ final FileObject file = scratchFolder.resolveFile("dir1/a.txt");
+
+ assertTrue(file.delete());
+ }
+
+ /**
+ * Deletes a non existent file
+ */
+ public void testDeleteNonExistantFile() throws Exception
+ {
+ final FileObject scratchFolder = createScratchFolder();
+
+ final FileObject file = scratchFolder.resolveFile("dir1/aa.txt");
+
+ assertFalse(file.delete());
+ }
+
+ /**
+ * deletes files
+ */
+ public void testDeleteAllFiles() throws Exception
+ {
+ final FileObject scratchFolder = createScratchFolder();
+
+ assertEquals(scratchFolder.delete(new FileTypeSelector(FileType.FILE)), 2);
+ }
+
+ /**
+ * deletes a.txt
+ */
+ public void testDeleteOneFiles() throws Exception
+ {
+ final FileObject scratchFolder = createScratchFolder();
+
+ assertEquals(scratchFolder.delete(new FileNameSelector("a.txt")), 1);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderRandomReadTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderRandomReadTests.java
new file mode 100644
index 0000000..df38414
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderRandomReadTests.java
@@ -0,0 +1,101 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.RandomAccessContent;
+import org.apache.commons.vfs2.util.RandomAccessMode;
+
+/**
+ * Random read-only test case for file providers.
+ *
+ * @version $Id$
+ */
+public class ProviderRandomReadTests
+ 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[] getRequiredCaps()
+ {
+ return new Capability[]
+ {
+ Capability.GET_TYPE,
+ Capability.RANDOM_ACCESS_READ
+ };
+ }
+
+ /**
+ * Read a file
+ */
+ public void testRandomRead() throws Exception
+ {
+ FileObject file = null;
+ try
+ {
+ file = getReadFolder().resolveFile("file1.txt");
+ final RandomAccessContent ra = file.getContent().getRandomAccessContent(RandomAccessMode.READ);
+
+ // read first byte
+ byte c = ra.readByte();
+ assertEquals(c, TEST_DATA.charAt(0));
+ assertEquals("fp", ra.getFilePointer(), 1);
+
+ // start at pos 4
+ ra.seek(3);
+ c = ra.readByte();
+ assertEquals(c, TEST_DATA.charAt(3));
+ assertEquals("fp", ra.getFilePointer(), 4);
+
+ c = ra.readByte();
+ assertEquals(c, TEST_DATA.charAt(4));
+ assertEquals("fp", ra.getFilePointer(), 5);
+
+ // restart at pos 4
+ ra.seek(3);
+ c = ra.readByte();
+ assertEquals(c, TEST_DATA.charAt(3));
+ assertEquals("fp", ra.getFilePointer(), 4);
+
+ c = ra.readByte();
+ assertEquals(c, TEST_DATA.charAt(4));
+ assertEquals("fp", ra.getFilePointer(), 5);
+
+ // advance to pos 11
+ ra.seek(10);
+ c = ra.readByte();
+ assertEquals(c, TEST_DATA.charAt(10));
+ assertEquals("fp", ra.getFilePointer(), 11);
+
+ c = ra.readByte();
+ assertEquals(c, TEST_DATA.charAt(11));
+ assertEquals("fp", ra.getFilePointer(), 12);
+ }
+ finally
+ {
+ if (file != null)
+ {
+ file.close();
+ }
+ }
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderRandomReadWriteTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderRandomReadWriteTests.java
new file mode 100644
index 0000000..5c223b6
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderRandomReadWriteTests.java
@@ -0,0 +1,114 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.RandomAccessContent;
+import org.apache.commons.vfs2.Selectors;
+import org.apache.commons.vfs2.util.RandomAccessMode;
+
+/**
+ * Random read and write test case for file providers.
+ *
+ * @version $Id$
+ */
+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[] getRequiredCaps()
+ {
+ 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
+ {
+ final FileObject scratchFolder = getWriteFolder();
+
+ // Make sure the test folder is empty
+ scratchFolder.delete(Selectors.EXCLUDE_SELF);
+ scratchFolder.createFolder();
+
+ return scratchFolder;
+ }
+
+ /**
+ * Writes a file
+ */
+ public void testRandomWrite() throws Exception
+ {
+ FileObject file = null;
+ try
+ {
+ file = createScratchFolder().resolveFile("random_write.txt");
+ file.createFile();
+ final RandomAccessContent ra = file.getContent().getRandomAccessContent(RandomAccessMode.READWRITE);
+
+ // write first byte
+ ra.writeByte(TEST_DATA.charAt(0));
+
+ // start at pos 4
+ ra.seek(3);
+ ra.writeByte(TEST_DATA.charAt(3));
+ ra.writeByte(TEST_DATA.charAt(4));
+
+ // restart at pos 4 (but overwrite with different content)
+ ra.seek(3);
+ ra.writeByte(TEST_DATA.charAt(7));
+ ra.writeByte(TEST_DATA.charAt(8));
+
+ // advance to pos 11
+ ra.seek(10);
+ ra.writeByte(TEST_DATA.charAt(10));
+ ra.writeByte(TEST_DATA.charAt(11));
+
+ // now read
+ ra.seek(0);
+ assertEquals(ra.readByte(), TEST_DATA.charAt(0));
+
+ ra.seek(3);
+ assertEquals(ra.readByte(), TEST_DATA.charAt(7));
+ assertEquals(ra.readByte(), TEST_DATA.charAt(8));
+
+ ra.seek(10);
+ assertEquals(ra.readByte(), TEST_DATA.charAt(10));
+ assertEquals(ra.readByte(), TEST_DATA.charAt(11));
+ }
+ finally
+ {
+ if (file != null)
+ {
+ file.close();
+ }
+ }
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderRandomSetLengthTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderRandomSetLengthTests.java
new file mode 100644
index 0000000..c7200d0
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderRandomSetLengthTests.java
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import java.io.IOException;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.RandomAccessContent;
+import org.apache.commons.vfs2.Selectors;
+import org.apache.commons.vfs2.util.RandomAccessMode;
+import org.junit.Assert;
+
+/**
+ * Random set length test cases for file providers.
+ *
+ * @version $Id$
+ */
+public class ProviderRandomSetLengthTests extends AbstractProviderTestCase
+{
+ private static final String TEST_DATA = "This is a test file.";
+
+ /**
+ * Sets up a scratch folder for the test to use.
+ */
+ protected FileObject createScratchFolder() throws Exception
+ {
+ final FileObject scratchFolder = this.getWriteFolder();
+
+ // Make sure the test folder is empty
+ scratchFolder.delete(Selectors.EXCLUDE_SELF);
+ scratchFolder.createFolder();
+
+ return scratchFolder;
+ }
+
+ /**
+ * Returns the capabilities required by the tests of this test case.
+ */
+ @Override
+ protected Capability[] getRequiredCaps()
+ {
+ return new Capability[]
+ {
+ Capability.GET_TYPE,
+ Capability.RANDOM_ACCESS_READ,
+ Capability.RANDOM_ACCESS_WRITE,
+ Capability.RANDOM_ACCESS_SET_LENGTH };
+ }
+
+ /**
+ * Writes a file
+ */
+ public void testRandomSetLength() throws Exception
+ {
+ FileObject file = null;
+ try
+ {
+ file = this.createScratchFolder().resolveFile("random_write.txt");
+ file.createFile();
+ final RandomAccessContent ra = file.getContent().getRandomAccessContent(RandomAccessMode.READWRITE);
+
+ // Write long string
+ ra.writeBytes(TEST_DATA);
+ Assert.assertEquals(TEST_DATA.length(), ra.length());
+
+ // Shrink to length 1
+ ra.setLength(1);
+ Assert.assertEquals(1, ra.length());
+ // now read 1
+ ra.seek(0);
+ Assert.assertEquals(ra.readByte(), TEST_DATA.charAt(0));
+
+ try
+ {
+ ra.readByte();
+ Assert.fail("Expected " + Exception.class.getName());
+ } catch (final IOException e)
+ {
+ // Expected
+ }
+
+ // Grow to length 2
+ ra.setLength(2);
+ Assert.assertEquals(2, ra.length());
+ // We have an undefined extra byte
+ ra.seek(1);
+ ra.readByte();
+
+ } finally
+ {
+ if (file != null)
+ {
+ file.close();
+ }
+ }
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderReadTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderReadTests.java
new file mode 100644
index 0000000..5841cf4
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderReadTests.java
@@ -0,0 +1,396 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileContent;
+import org.apache.commons.vfs2.FileContentInfo;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.junit.Assert;
+
+/**
+ * Read-only test cases for file providers.
+ * <p>
+ * TODO - Test getLastModified(), getAttribute().
+ */
+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[] getRequiredCaps()
+ {
+ 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.
+ */
+ 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
+ {
+ // Setup the structure
+ final List<FileInfo> queueExpected = new ArrayList<FileInfo>();
+ queueExpected.add(expected);
+
+ final List<FileObject> queueActual = new ArrayList<FileObject>();
+ queueActual.add(folder);
+
+ while (queueActual.size() > 0)
+ {
+ final FileObject file = queueActual.remove(0);
+ final FileInfo info = queueExpected.remove(0);
+
+ // Check the type is correct
+ assertSame(info.type, file.getType());
+
+ if (info.type == FileType.FILE)
+ {
+ continue;
+ }
+
+ // Check children
+ final FileObject[] children = file.getChildren();
+
+ // Make sure all children were found
+ assertNotNull(children);
+ int length = children.length;
+ if (info.children.size() != children.length)
+ {
+ for (final FileObject element : children)
+ {
+ if (element.getName().getBaseName().startsWith("."))
+ {
+ --length;
+ continue;
+ }
+ System.out.println(element.getName());
+ }
+ }
+
+ assertEquals("count children of \"" + file.getName() + "\"", info.children.size(), length);
+
+ // Recursively check each child
+ for (final FileObject child : children)
+ {
+ final String childName = child.getName().getBaseName();
+ if (childName.startsWith("."))
+ {
+ continue;
+ }
+ final FileInfo childInfo = info.children.get(childName);
+
+ // Make sure the child is expected
+ assertNotNull(childInfo);
+
+ // Add to the queue of files to check
+ queueExpected.add(childInfo);
+ queueActual.add(child);
+ }
+ }
+ }
+
+ /**
+ * Tests type determination.
+ */
+ 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());
+ }
+
+ /**
+ * Tests the contents of root of file system can be listed.
+ */
+ 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 FileObjects can be sorted.
+ */
+ 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++)
+ {
+ final FileObject expected = expectedFiles.get(i);
+ final FileObject actual = actualFiles[i];
+ assertEquals(expected, actual);
+ }
+ }
+
+ /**
+ * Tests that folders have no content.
+ */
+ public void testFolderContent() throws Exception
+ {
+ if (getFileSystem().hasCapability(Capability.DIRECTORY_READ_CONTENT))
+ {
+ // test wont fail
+ return;
+ }
+
+ // Try getting the content of a folder
+ final FileObject folder = getReadFolderDir1();
+ try
+ {
+ folder.getContent().getInputStream();
+ fail();
+ } catch (final FileSystemException e)
+ {
+ assertSameMessage("vfs.provider/read-not-file.error", folder, e);
+ }
+ }
+
+ /**
+ * Tests that test read folder is not hidden.
+ */
+ public void testFolderIsHidden() throws Exception
+ {
+ final FileObject folder = getReadFolderDir1();
+ Assert.assertFalse(folder.isHidden());
+ }
+
+ /**
+ * Tests that test read folder is readable.
+ */
+ public void testFolderIsReadable() throws Exception
+ {
+ final FileObject folder = getReadFolderDir1();
+ Assert.assertTrue(folder.isReadable());
+ }
+
+ public void testGetContent() throws Exception
+ {
+ final FileObject file = resolveFile1Txt();
+ assertTrue(file.exists());
+ final FileContent content = file.getContent();
+ assertNotNull(content);
+ }
+
+ public void testGetContentInfo() throws Exception
+ {
+ final FileObject file = resolveFile1Txt();
+ assertTrue(file.exists());
+ final FileContent content = file.getContent();
+ assertNotNull(content);
+ final FileContentInfo contentInfo = content.getContentInfo();
+ assertNotNull(contentInfo);
+ }
+
+ private FileObject resolveFile1Txt() throws FileSystemException
+ {
+ return getReadFolder().resolveFile("file1.txt");
+ }
+
+ /**
+ * Tests can read multiple time end of stream of empty file
+ */
+ public void testReadEmptyMultipleEOF() throws Exception
+ {
+ final FileObject file = getReadFolder().resolveFile("empty.txt");
+ assertTrue(file.exists());
+
+ // Start reading from the file
+ final InputStream instr = file.getContent().getInputStream();
+ try
+ {
+ assertEquals("read() from empty file should return EOF", -1, instr.read());
+
+ for(int i=0;i<5;i++)
+ {
+ assertEquals("multiple read() at EOF should return EOF", -1, instr.read());
+ }
+ }
+ finally
+ {
+ instr.close();
+ }
+ }
+
+ /**
+ * Tests can read multiple time end of stream
+ */
+ public void testReadFileEOFMultiple() throws Exception
+ {
+ final FileObject file = getReadFolder().resolveFile("file1.txt");
+ assertTrue(file.exists());
+ assertEquals("Expecting 20 bytes test-data file1.txt", 20, file.getContent().getSize());
+
+ // Start reading from the file
+ final InputStream instr = file.getContent().getInputStream();
+ try
+ {
+ byte[] buf = new byte[25];
+ assertEquals(20, instr.read(buf));
+
+ for(int i=0;i<5;i++)
+ {
+ assertEquals("multiple read(byte[]) at EOF should return EOF", -1, instr.read(buf));
+ }
+ }
+ finally
+ {
+ instr.close();
+ }
+ }
+
+ /**
+ * Tests can perform operations on a folder while reading from a different files.
+ */
+ public void testConcurrentReadFolder() throws Exception
+ {
+ final FileObject file = resolveFile1Txt();
+ assertTrue(file.exists());
+ final FileObject folder = getReadFolderDir1();
+ assertTrue(folder.exists());
+
+ // Start reading from the file
+ final InputStream instr = file.getContent().getInputStream();
+ try
+ {
+ // Do some operations
+ folder.exists();
+ folder.getType();
+ folder.getChildren();
+ } finally
+ {
+ instr.close();
+ }
+ }
+
+ /**
+ * Tests that findFiles() works.
+ */
+ public void testFindFiles() throws Exception
+ {
+ final FileInfo fileInfo = buildExpectedStructure();
+ final VerifyingFileSelector selector = new VerifyingFileSelector(fileInfo);
+
+ // Find the files
+ final FileObject[] actualFiles = getReadFolder().findFiles(selector);
+
+ // Compare actual and expected list of files
+ final List<FileObject> expectedFiles = selector.finish();
+ assertEquals(expectedFiles.size(), actualFiles.length);
+ final int count = expectedFiles.size();
+ for (int i = 0; i < count; i++)
+ {
+ final FileObject expected = expectedFiles.get(i);
+ final FileObject actual = actualFiles[i];
+ assertEquals(expected, actual);
+ }
+ }
+
+ /**
+ * Tests that we can traverse a folder that has JAR name.
+ */
+ 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 that a folder can't be layered.
+ */
+ 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
+ {
+ 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());
+ }
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderRenameTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderRenameTests.java
new file mode 100644
index 0000000..14cab90
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderRenameTests.java
@@ -0,0 +1,163 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.io.UnsupportedEncodingException;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.Selectors;
+
+/**
+ * File system test that check that a file system can be renamed.
+ */
+public class ProviderRenameTests
+ extends AbstractProviderTestCase
+{
+ /**
+ * Returns the capabilities required by the tests of this test case.
+ */
+ @Override
+ protected Capability[] getRequiredCaps()
+ {
+ 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
+ {
+ final FileObject scratchFolder = getWriteFolder();
+
+ // Make sure the test folder is empty
+ scratchFolder.delete(Selectors.EXCLUDE_SELF);
+ scratchFolder.createFolder();
+
+ return scratchFolder;
+ }
+
+ private void moveFile(final FileObject scratchFolder, final FileObject file, final String content)
+ throws FileSystemException, Exception
+ {
+ final FileObject fileMove = scratchFolder.resolveFile("file1move.txt");
+ assertTrue(!fileMove.exists());
+
+ file.moveTo(fileMove);
+
+ assertTrue(!file.exists());
+ assertTrue(fileMove.exists());
+
+ assertSameContent(content, fileMove);
+
+ // Delete the file.
+ assertTrue(fileMove.exists());
+ 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.";
+
+ final OutputStream os = file.getContent().getOutputStream();
+ try
+ {
+ os.write(content.getBytes("utf-8"));
+ }
+ finally
+ {
+ os.close();
+ }
+ assertSameContent(content, file);
+ return content;
+ }
+
+ /**
+ * Tests create-delete-create-a-file sequence on the same file system.
+ */
+ public void testRenameFile() throws Exception
+ {
+ final FileObject scratchFolder = createScratchFolder();
+
+ // Create direct child of the test folder
+ final FileObject file = scratchFolder.resolveFile("file1.txt");
+ assertTrue(!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);
+ }
+
+ /**
+ * Tests moving a file to empty folder.
+ * <P>
+ * This fails with VFS-558, but only with a CacheStrategy.ON_CALL.
+ */
+ public void testRenameFileIntoEmptyFolder() throws Exception
+ {
+ final FileObject scratchFolder = createScratchFolder();
+
+ // Create direct child of the test folder
+ final FileObject file = scratchFolder.resolveFile("file1.txt");
+ assertTrue(!file.exists());
+
+ final String content = createTestFile(file);
+
+ final FileObject destFolder = scratchFolder.resolveFile("empty-target-folder");
+ destFolder.createFolder();
+ assertTrue("new destination must be folder", destFolder.getType().hasChildren());
+ assertTrue("new destination must be emty", destFolder.getChildren().length == 0);
+
+ 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.
+ */
+ 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");
+ assertTrue(!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);
+ assertTrue(folder.getChildren().length == 0);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderTestConfig.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderTestConfig.java
new file mode 100644
index 0000000..53278f1
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderTestConfig.java
@@ -0,0 +1,61 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FilesCache;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+
+/**
+ * Test configuration for a file system.
+ *
+ */
+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>/write-tests
+ * </ul>
+ */
+ FileObject getBaseTestFolder(FileSystemManager manager) throws Exception;
+
+ /**
+ * Returns the filesCache implementation used for tests.
+ */
+ FilesCache getFilesCache();
+
+ /**
+ * Whether or not the root of test file system is accessible.
+ *
+ * For example, with the default Jackrabbit (WebDAV) server, the root is not accessible, but deeper paths are OK.
+ *
+ * @return Whether or not the root of test file system is accessible.
+ */
+ boolean isFileSystemRootAccessible();
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderTestSuite.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderTestSuite.java
new file mode 100644
index 0000000..a7fc478
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderTestSuite.java
@@ -0,0 +1,78 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import org.apache.commons.vfs2.impl.test.VfsClassLoaderTests;
+
+/**
+ * The suite of tests for a file system.
+ */
+public class ProviderTestSuite
+ extends AbstractTestSuite
+{
+ /**
+ * Adds the tests for a file system to this suite.
+ */
+ public ProviderTestSuite(final ProviderTestConfig providerConfig) throws Exception
+ {
+ this(providerConfig, "", false, false);
+ }
+
+ /**
+ * Adds the tests for a file system to this suite. Provider has an empty directory.
+ */
+ public ProviderTestSuite(final ProviderTestConfig providerConfig,
+ final boolean addEmptyDir) throws Exception
+ {
+ this(providerConfig, "", false, addEmptyDir);
+ }
+
+
+
+ protected ProviderTestSuite(final ProviderTestConfig providerConfig,
+ final String prefix,
+ final boolean nested,
+ final boolean addEmptyDir)
+ throws Exception
+ {
+ super(providerConfig, prefix, nested, addEmptyDir);
+ }
+
+ /**
+ * Adds base tests - excludes the nested test cases.
+ */
+ @Override
+ protected void addBaseTests() throws Exception
+ {
+ addTests(ProviderCacheStrategyTests.class);
+ addTests(UriTests.class);
+ addTests(NamingTests.class);
+ addTests(ContentTests.class);
+ addTests(ProviderReadTests.class);
+ addTests(ProviderWriteTests.class);
+ addTests(ProviderWriteAppendTests.class);
+ addTests(ProviderRandomReadTests.class);
+ addTests(ProviderRandomReadWriteTests.class);
+ addTests(ProviderRandomSetLengthTests.class);
+ addTests(ProviderRenameTests.class);
+ addTests(ProviderDeleteTests.class);
+ addTests(LastModifiedTests.class);
+ addTests(UrlTests.class);
+ addTests(UrlStructureTests.class);
+ addTests(VfsClassLoaderTests.class);
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderWriteAppendTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderWriteAppendTests.java
new file mode 100644
index 0000000..50b9431
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderWriteAppendTests.java
@@ -0,0 +1,112 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import java.io.OutputStream;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.Selectors;
+
+/**
+ * File system test that check that a file system can be modified.
+ */
+public class ProviderWriteAppendTests
+ extends AbstractProviderTestCase
+{
+ /**
+ * Returns the capabilities required by the tests of this test case.
+ */
+ @Override
+ protected Capability[] getRequiredCaps()
+ {
+ 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
+ {
+ final FileObject scratchFolder = getWriteFolder();
+
+ // Make sure the test folder is empty
+ scratchFolder.delete(Selectors.EXCLUDE_SELF);
+ scratchFolder.createFolder();
+
+ return scratchFolder;
+ }
+
+ /**
+ * Tests create-delete-create-a-file sequence on the same file system.
+ */
+ public void testAppendContent() throws Exception
+ {
+ final FileObject scratchFolder = createScratchFolder();
+
+ // Create direct child of the test folder
+ final FileObject file = scratchFolder.resolveFile("file1.txt");
+ assertTrue(!file.exists());
+
+ // Create the source file
+ final String content = "Here is some sample content for the file. Blah Blah Blah.";
+ final String contentAppend = content + content;
+
+ final OutputStream os = file.getContent().getOutputStream();
+ try
+ {
+ os.write(content.getBytes("utf-8"));
+ }
+ finally
+ {
+ os.close();
+ }
+ assertSameContent(content, file);
+
+ // Append to the new file
+ final OutputStream os2 = file.getContent().getOutputStream(true);
+ try
+ {
+ os2.write(content.getBytes("utf-8"));
+ }
+ finally
+ {
+ os2.close();
+ }
+ assertSameContent(contentAppend, file);
+
+ // Make sure we can copy the new file to another file on the same filesystem
+ final FileObject fileCopy = scratchFolder.resolveFile("file1copy.txt");
+ assertTrue(!fileCopy.exists());
+ fileCopy.copyFrom(file, Selectors.SELECT_SELF);
+
+ assertSameContent(contentAppend, fileCopy);
+
+ // Delete the file.
+ assertTrue(fileCopy.exists());
+ assertTrue(fileCopy.delete());
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderWriteTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderWriteTests.java
new file mode 100644
index 0000000..10afb52
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/ProviderWriteTests.java
@@ -0,0 +1,857 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.Set;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileChangeEvent;
+import org.apache.commons.vfs2.FileContent;
+import org.apache.commons.vfs2.FileListener;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.Selectors;
+import org.junit.Assert;
+
+/**
+ * File system test that check that a file system can be modified.
+ */
+public class ProviderWriteTests
+ extends AbstractProviderTestCase
+{
+
+ protected FileObject getReadFolderDir1() throws FileSystemException
+ {
+ return getReadFolder().resolveFile("dir1");
+ }
+
+ /**
+ * Returns the capabilities required by the tests of this test case.
+ */
+ @Override
+ protected Capability[] getRequiredCaps()
+ {
+ return new Capability[]
+ {
+ Capability.CREATE,
+ Capability.DELETE,
+ Capability.GET_TYPE,
+ Capability.LIST_CHILDREN,
+ Capability.READ_CONTENT,
+ Capability.WRITE_CONTENT
+ };
+ }
+
+ /**
+ * Sets up a scratch folder for the test to use.
+ */
+ protected FileObject createScratchFolder() throws Exception
+ {
+ final FileObject scratchFolder = getWriteFolder();
+
+ // Make sure the test folder is empty
+ scratchFolder.delete(Selectors.EXCLUDE_SELF);
+ scratchFolder.createFolder();
+
+ return scratchFolder;
+ }
+
+ /**
+ * Tests folder creation.
+ */
+ public void testFolderCreate() throws Exception
+ {
+ final FileObject scratchFolder = createScratchFolder();
+
+ // Create direct child of the test folder
+ FileObject folder = scratchFolder.resolveFile("dir1");
+ assertTrue(!folder.exists());
+ folder.createFolder();
+ assertTrue(folder.exists());
+ assertSame(FileType.FOLDER, folder.getType());
+ assertTrue(folder.isFolder());
+ assertEquals(0, folder.getChildren().length);
+
+ // Create a descendant, where the intermediate folders don't exist
+ folder = scratchFolder.resolveFile("dir2/dir1/dir1");
+ assertTrue(!folder.exists());
+ assertTrue(!folder.getParent().exists());
+ assertTrue(!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());
+
+ // Test creating a folder that already exists
+ assertTrue(folder.exists());
+ folder.createFolder();
+ }
+
+ /**
+ * Tests file creation
+ */
+ public void testFileCreate() throws Exception
+ {
+ final FileObject scratchFolder = createScratchFolder();
+
+ // Create direct child of the test folder
+ FileObject file = scratchFolder.resolveFile("file1.txt");
+ assertTrue(!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 direct child of the test folder - special name
+ file = scratchFolder.resolveFile("file1%25.txt");
+ assertTrue(!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 a descendant, where the intermediate folders don't exist
+ file = scratchFolder.resolveFile("dir1/dir1/file1.txt");
+ assertTrue(!file.exists());
+ assertTrue(!file.getParent().exists());
+ assertTrue(!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());
+
+ // Test creating a file that already exists
+ assertTrue(file.exists());
+ file.createFile();
+ assertTrue(file.exists());
+ assertTrue(file.isReadable());
+ assertTrue(file.isWriteable());
+ }
+
+ /**
+ * Tests file/folder creation with mismatched types.
+ */
+ public void testFileCreateMismatched() 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());
+
+ // Attempt to create a file that already exists as a folder
+ try
+ {
+ folder.createFile();
+ fail();
+ }
+ catch (final FileSystemException exc)
+ {
+ }
+
+ // Attempt to create a folder that already exists as a file
+ try
+ {
+ file.createFolder();
+ fail();
+ }
+ catch (final FileSystemException exc)
+ {
+ }
+
+ // 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)
+ {
+ }
+ }
+
+ /**
+ * Tests deletion
+ */
+ public void testDelete() throws Exception
+ {
+ // Set-up the test structure
+ final FileObject folder = createScratchFolder();
+ folder.resolveFile("file1.txt").createFile();
+ folder.resolveFile("file%25.txt").createFile();
+ folder.resolveFile("emptydir").createFolder();
+ folder.resolveFile("dir1/file1.txt").createFile();
+ folder.resolveFile("dir1/dir2/file2.txt").createFile();
+
+ // Delete a file
+ FileObject file = folder.resolveFile("file1.txt");
+ assertTrue(file.exists());
+ file.deleteAll();
+ assertTrue(!file.exists());
+
+ // Delete a special name file
+ file = folder.resolveFile("file%25.txt");
+ assertTrue(file.exists());
+ file.deleteAll();
+ assertTrue(!file.exists());
+
+ // Delete an empty folder
+ file = folder.resolveFile("emptydir");
+ assertTrue(file.exists());
+ file.deleteAll();
+ assertTrue(!file.exists());
+
+ // Recursive delete
+ file = folder.resolveFile("dir1");
+ final FileObject file2 = file.resolveFile("dir2/file2.txt");
+ assertTrue(file.exists());
+ assertTrue(file2.exists());
+ file.deleteAll();
+ assertTrue(!file.exists());
+ assertTrue(!file2.exists());
+
+ // Delete a file that does not exist
+ file = folder.resolveFile("some-folder/some-file");
+ assertTrue(!file.exists());
+ file.deleteAll();
+ assertTrue(!file.exists());
+ }
+
+ /**
+ * Tests deletion
+ */
+ public void testDeleteAllDescendents() throws Exception
+ {
+ // Set-up the test structure
+ final FileObject folder = createScratchFolder();
+ folder.resolveFile("file1.txt").createFile();
+ folder.resolveFile("file%25.txt").createFile();
+ folder.resolveFile("emptydir").createFolder();
+ folder.resolveFile("dir1/file1.txt").createFile();
+ folder.resolveFile("dir1/dir2/file2.txt").createFile();
+
+ // Delete a file
+ FileObject file = folder.resolveFile("file1.txt");
+ assertTrue(file.exists());
+ file.deleteAll();
+ assertTrue(!file.exists());
+
+ // Delete a special name file
+ file = folder.resolveFile("file%25.txt");
+ assertTrue(file.exists());
+ file.deleteAll();
+ assertTrue(!file.exists());
+
+ // Delete an empty folder
+ file = folder.resolveFile("emptydir");
+ assertTrue(file.exists());
+ file.deleteAll();
+ assertTrue(!file.exists());
+
+ // Recursive delete
+ file = folder.resolveFile("dir1");
+ final FileObject file2 = file.resolveFile("dir2/file2.txt");
+ assertTrue(file.exists());
+ assertTrue(file2.exists());
+ file.deleteAll();
+ assertTrue(!file.exists());
+ assertTrue(!file2.exists());
+
+ // Delete a file that does not exist
+ file = folder.resolveFile("some-folder/some-file");
+ assertTrue(!file.exists());
+ file.deleteAll();
+ assertTrue(!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 filesystem type. This was a problem
+ * w/ FTP.
+ */
+ public void testCopySameFileSystem() throws Exception
+ {
+ final FileObject scratchFolder = createScratchFolder();
+
+ // Create direct child of the test folder
+ final FileObject file = scratchFolder.resolveFile("file1.txt");
+ assertTrue(!file.exists());
+
+ // Create the source file
+ final String content = "Here is some sample content for the file. Blah Blah Blah.";
+ final OutputStream os = file.getContent().getOutputStream();
+ try
+ {
+ os.write(content.getBytes("utf-8"));
+ }
+ finally
+ {
+ os.close();
+ }
+
+ 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");
+ assertTrue(!fileCopy.exists());
+ fileCopy.copyFrom(file, Selectors.SELECT_SELF);
+
+ assertSameContent(content, fileCopy);
+ }
+
+ /**
+ * Tests overwriting a file on the same file system.
+ */
+ public void testCopyFromOverwriteSameFileSystem() throws Exception
+ {
+ final FileObject scratchFolder = createScratchFolder();
+
+ // Create direct child of the test folder
+ final FileObject file = scratchFolder.resolveFile("file1.txt");
+ assertTrue(!file.exists());
+
+ // Create the source file
+ final String content = "Here is some sample content for the file. Blah Blah Blah.";
+ final OutputStream os = file.getContent().getOutputStream();
+ try
+ {
+ os.write(content.getBytes("utf-8"));
+ }
+ finally
+ {
+ os.close();
+ }
+
+ 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");
+ assertTrue(!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 create-delete-create-a-file sequence on the same file system.
+ */
+ public void testCreateDeleteCreateSameFileSystem() throws Exception
+ {
+ final FileObject scratchFolder = createScratchFolder();
+
+ // Create direct child of the test folder
+ final FileObject file = scratchFolder.resolveFile("file1.txt");
+ assertTrue(!file.exists());
+
+ // Create the source file
+ final String content = "Here is some sample content for the file. Blah Blah Blah.";
+ final OutputStream os = file.getContent().getOutputStream();
+ try
+ {
+ os.write(content.getBytes("utf-8"));
+ }
+ finally
+ {
+ os.close();
+ }
+
+ 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");
+ assertTrue(!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
+ assertTrue(!fileCopy.exists());
+ fileCopy.copyFrom(file, Selectors.SELECT_SELF);
+
+ assertSameContent(content, fileCopy);
+ }
+
+ /**
+ * Tests that test read folder is not hidden.
+ */
+ public void testFolderIsHidden() throws Exception
+ {
+ final FileObject folder = getReadFolderDir1();
+ Assert.assertFalse(folder.isHidden());
+ }
+
+ /**
+ * Tests that test read folder is readable.
+ */
+ public void testFolderIsReadable() throws Exception
+ {
+ final FileObject folder = getReadFolderDir1();
+ Assert.assertTrue(folder.isReadable());
+ }
+
+ /**
+ * Tests that test folder iswritable.
+ */
+ public void testFolderIsWritable() throws Exception
+ {
+ final FileObject folder = getWriteFolder().resolveFile("dir1");
+ Assert.assertTrue(folder.isWriteable());
+ }
+
+ /**
+ * Test that children are handled correctly by create and delete.
+ */
+ public void testListChildren() throws Exception
+ {
+ final FileObject folder = createScratchFolder();
+ final HashSet<String> names = new HashSet<String>();
+
+ // Make sure the folder is empty
+ assertEquals(0, folder.getChildren().length);
+
+ // Create a child folder
+ folder.resolveFile("dir1").createFolder();
+ names.add("dir1");
+ assertSameFileSet(names, folder.getChildren());
+
+ // Create a child file
+ folder.resolveFile("file1.html").createFile();
+ names.add("file1.html");
+ assertSameFileSet(names, folder.getChildren());
+
+ // Create a descendent
+ folder.resolveFile("dir2/file1.txt").createFile();
+ names.add("dir2");
+ assertSameFileSet(names, folder.getChildren());
+
+ // Create a child file via an output stream
+ final OutputStream outstr = folder.resolveFile("file2.txt").getContent().getOutputStream();
+ outstr.close();
+ names.add("file2.txt");
+ assertSameFileSet(names, folder.getChildren());
+
+ // Delete a child folder
+ folder.resolveFile("dir1").deleteAll();
+ names.remove("dir1");
+ assertSameFileSet(names, folder.getChildren());
+
+ // Delete a child file
+ folder.resolveFile("file1.html").deleteAll();
+ names.remove("file1.html");
+ assertSameFileSet(names, folder.getChildren());
+
+ // Recreate the folder
+ folder.deleteAll();
+ folder.createFolder();
+ assertEquals(0, folder.getChildren().length);
+ }
+
+ /**
+ * Check listeners are notified of changes.
+ */
+ public void testListener() throws Exception
+ {
+ final FileObject baseFile = createScratchFolder();
+
+ final FileObject child = baseFile.resolveFile("newfile.txt");
+ assertTrue(!child.exists());
+
+ final FileSystem fs = baseFile.getFileSystem();
+ final TestListener listener = new TestListener(child);
+ fs.addListener(child, listener);
+ try
+ {
+ // Create as a folder
+ listener.addCreateEvent();
+ child.createFolder();
+ listener.assertFinished();
+
+ // Create the folder again. Should not get an event.
+ child.createFolder();
+
+ // Delete
+ listener.addDeleteEvent();
+ child.delete();
+ listener.assertFinished();
+
+ // Delete again. Should not get an event
+ child.delete();
+
+ // Create as a file
+ listener.addCreateEvent();
+ child.createFile();
+ listener.assertFinished();
+
+ // Create the file again. Should not get an event
+ child.createFile();
+
+ listener.addDeleteEvent();
+ child.delete();
+
+ // Create as a file, by writing to it.
+ listener.addCreateEvent();
+ child.getContent().getOutputStream().close();
+ listener.assertFinished();
+
+ // Recreate the file by writing to it
+ child.getContent().getOutputStream().close();
+
+ // Copy another file over the top
+ final FileObject otherChild = baseFile.resolveFile("folder1");
+ otherChild.createFolder();
+ listener.addDeleteEvent();
+ listener.addCreateEvent();
+ child.copyFrom(otherChild, Selectors.SELECT_SELF);
+ listener.assertFinished();
+
+ }
+ finally
+ {
+ fs.removeListener(child, listener);}
+ }
+
+ /**
+ * Ensures the names of a set of files match an expected set.
+ */
+ 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()));
+ }
+ }
+
+ /**
+ * A test listener.
+ */
+ private static class TestListener implements FileListener
+ {
+ private final FileObject file;
+ private final ArrayList<Object> events = new ArrayList<Object>();
+ private static final Object CREATE = "create";
+ private static final Object DELETE = "delete";
+ private static final Object CHANGED = "changed";
+
+ public TestListener(final FileObject file)
+ {
+ this.file = file;
+ }
+
+ /**
+ * Called when a file is created.
+ */
+ @Override
+ public void fileCreated(final FileChangeEvent event)
+ {
+ assertTrue("Unexpected create event", events.size() > 0);
+ assertSame("Expecting a create event", CREATE, events.remove(0));
+ assertEquals(file, event.getFile());
+ try
+ {
+ assertTrue(file.exists());
+ }
+ catch (final FileSystemException e)
+ {
+ fail();
+ }
+ }
+
+ /**
+ * Called when a file is deleted.
+ */
+ @Override
+ public void fileDeleted(final FileChangeEvent event)
+ {
+ assertTrue("Unexpected delete event", events.size() > 0);
+ assertSame("Expecting a delete event", DELETE, events.remove(0));
+ assertEquals(file, event.getFile());
+ try
+ {
+ assertTrue(!file.exists());
+ }
+ catch (final FileSystemException e)
+ {
+ fail();
+ }
+ }
+
+ @Override
+ public void fileChanged(final FileChangeEvent event) throws Exception
+ {
+ assertTrue("Unexpected changed event", events.size() > 0);
+ assertSame("Expecting a changed event", CHANGED, events.remove(0));
+ assertEquals(file, event.getFile());
+ try
+ {
+ assertTrue(!file.exists());
+ }
+ catch (final FileSystemException e)
+ {
+ fail();
+ }
+ }
+
+ public void addCreateEvent()
+ {
+ events.add(CREATE);
+ }
+
+ public void addDeleteEvent()
+ {
+ events.add(DELETE);
+ }
+
+ public void assertFinished()
+ {
+ assertEquals("Missing event", 0, events.size());
+ }
+ }
+
+ /**
+ * Tests file write to and from the same filesystem type
+ */
+ public void testWriteSameFileSystem() throws Exception
+ {
+ final FileObject scratchFolder = createScratchFolder();
+
+ // Create direct child of the test folder
+ final FileObject fileSource = scratchFolder.resolveFile("file1.txt");
+ assertTrue(!fileSource.exists());
+
+ // Create the source file
+ final String expectedString = "Here is some sample content for the file. Blah Blah Blah.";
+ final OutputStream expectedOutputStream = fileSource.getContent().getOutputStream();
+ try
+ {
+ expectedOutputStream.write(expectedString.getBytes("utf-8"));
+ }
+ finally
+ {
+ expectedOutputStream.close();
+ }
+
+ assertSameContent(expectedString, fileSource);
+
+ // Make sure we can copy the new file to another file on the same filesystem
+ final FileObject fileTarget = scratchFolder.resolveFile("file1copy.txt");
+ assertTrue(!fileTarget.exists());
+
+ final FileContent contentSource = fileSource.getContent();
+ //
+ // Tests FileContent#write(FileContent)
+ contentSource.write(fileTarget.getContent());
+ assertSameContent(expectedString, fileTarget);
+ //
+ // Tests FileContent#write(OutputStream)
+ OutputStream outputStream = fileTarget.getContent().getOutputStream();
+ try {
+ contentSource.write(outputStream);
+ } finally {
+ outputStream.close();
+ }
+ assertSameContent(expectedString, fileTarget);
+ //
+ // Tests FileContent#write(OutputStream, int)
+ outputStream = fileTarget.getContent().getOutputStream();
+ try {
+ contentSource.write(outputStream, 1234);
+ } finally {
+ outputStream.close();
+ }
+ assertSameContent(expectedString, fileTarget);
+ }
+
+ /**
+ * Tests overwriting a file on the same file system.
+ */
+ public void testOverwriteSameFileSystem() throws Exception
+ {
+ final FileObject scratchFolder = createScratchFolder();
+
+ // Create direct child of the test folder
+ final FileObject file = scratchFolder.resolveFile("file1.txt");
+ assertTrue(!file.exists());
+
+ // Create the source file
+ final String content = "Here is some sample content for the file. Blah Blah Blah.";
+ final OutputStream os = file.getContent().getOutputStream();
+ try
+ {
+ os.write(content.getBytes("utf-8"));
+ }
+ finally
+ {
+ os.close();
+ }
+
+ 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");
+ 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);
+
+ 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/trunk/core/src/test/java/org/apache/commons/vfs2/test/UriTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/UriTests.java
new file mode 100644
index 0000000..0534ceb
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/UriTests.java
@@ -0,0 +1,58 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+
+/**
+ * Absolute URI test cases.
+ */
+public class UriTests
+ extends AbstractProviderTestCase
+{
+ /**
+ * Returns the capabilities required by the tests of this test case.
+ */
+ @Override
+ protected Capability[] getRequiredCaps()
+ {
+ return new Capability[]{Capability.URI};
+ }
+
+ /**
+ * Tests resolution of absolute URI.
+ */
+ public void testAbsoluteURI() throws Exception
+ {
+ final FileObject readFolder = getReadFolder();
+
+ // Try fetching base folder again by its URI
+ final String uri = readFolder.getName().getURI();
+ FileObject file = getManager().resolveFile(uri, readFolder.getFileSystem().getFileSystemOptions());
+ assertSame("file object", readFolder, file);
+
+ // Try fetching the filesystem root by its URI
+ final String rootUri = readFolder.getName().getRootURI();
+ file = getManager().resolveFile(rootUri, readFolder.getFileSystem().getFileSystemOptions());
+ assertSame(readFolder.getFileSystem().getRoot(), file);
+ assertEquals(rootUri, file.getName().getRootURI());
+ assertEquals(rootUri, file.getName().getURI());
+ assertEquals(FileName.ROOT_PATH, file.getName().getPath());
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/test/UrlStructureTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/UrlStructureTests.java
new file mode 100644
index 0000000..179e6bf
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/UrlStructureTests.java
@@ -0,0 +1,69 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import java.io.IOException;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileObject;
+
+/**
+ * URL Test cases for providers that supply structural info.
+ */
+public class UrlStructureTests
+ extends AbstractProviderTestCase
+{
+ /**
+ * Returns the capabilities required by the tests of this test case.
+ */
+ @Override
+ protected Capability[] getRequiredCaps()
+ {
+ return new Capability[]
+ {
+ Capability.GET_TYPE,
+ Capability.URI
+ };
+ }
+
+ /**
+ * Tests that folders have no content.
+ */
+ public void testFolderURL() throws Exception
+ {
+ final FileObject folder = getReadFolder().resolveFile("dir1");
+ if (folder.getFileSystem().hasCapability(Capability.DIRECTORY_READ_CONTENT))
+ {
+ // test might not fail on e.g. HttpFileSystem as there are no direcotries.
+ // A Directory do have a content on http. e.g a generated directory listing or the index.html page.
+ return;
+ }
+
+ assertTrue(folder.exists());
+
+ // Try getting the content of a folder
+ try
+ {
+ folder.getURL().openConnection().getInputStream();
+ fail();
+ }
+ catch (final IOException e)
+ {
+ assertSameMessage("vfs.provider/read-not-file.error", folder, e);
+ }
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/test/UrlTests.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/UrlTests.java
new file mode 100644
index 0000000..ec269f1
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/UrlTests.java
@@ -0,0 +1,132 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import java.io.IOException;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLConnection;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemOptions;
+
+/**
+ * URL test cases for providers.
+ */
+public class UrlTests
+ extends AbstractProviderTestCase
+{
+ /**
+ * 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.
+ */
+ @Override
+ protected Capability[] getRequiredCaps()
+ {
+ return new Capability[]{Capability.URI};
+ }
+
+ /**
+ * Tests url.
+ */
+ public void testURL() throws Exception
+ {
+ final FileObject file = getReadFolder().resolveFile("some-dir/");
+ final URL url = file.getURL();
+
+ assertEquals(file.getName().getURI(), url.toExternalForm());
+
+ final URL parentURL;
+ try
+ {
+ parentURL = new URL(url, "..");
+ }
+ catch (final MalformedURLException e)
+ {
+ throw e;
+ }
+ assertEquals(file.getParent().getURL(), parentURL);
+
+ final URL rootURL = new URL(url, "/");
+ assertEquals(file.getFileSystem().getRoot().getURL(), rootURL);
+ }
+
+ /**
+ * Tests content.
+ */
+ public void testURLContent() throws Exception
+ {
+ // Test non-empty file
+ FileObject file = getReadFolder().resolveFile("file1.txt");
+ assertTrue(file.exists());
+
+ URLConnection urlCon = file.getURL().openConnection();
+ assertSameURLContent(FILE1_CONTENT, urlCon);
+
+ // Test empty file
+ file = getReadFolder().resolveFile("empty.txt");
+ assertTrue(file.exists());
+
+ urlCon = file.getURL().openConnection();
+ assertSameURLContent("", urlCon);
+ }
+
+ /**
+ * Tests content.
+ */
+ public void testURLContentProvider() throws Exception
+ {
+ // Test non-empty file
+ FileObject file = getReadFolder().resolveFile("file1.txt");
+ assertTrue(file.exists());
+
+ String uri = file.getURL().toExternalForm();
+ FileSystemOptions options = getReadFolder().getFileSystem().getFileSystemOptions();
+
+ FileObject f1 = getManager().resolveFile(uri, options);
+ FileObject f2 = getManager().resolveFile(uri, options);
+
+ assertEquals("Two files resolved by URI must be equals on " + uri, f1, f2);
+ assertSame("Resolving two times should not produce new filesystem on " + uri, f1.getFileSystem(), f2.getFileSystem());
+ }
+
+ /**
+ * Tests that unknown files have no content.
+ */
+ public void testUnknownURL() throws Exception
+ {
+ // Try getting the content of an unknown file
+ final FileObject unknownFile = getReadFolder().resolveFile("unknown-file");
+ assertFalse(unknownFile.exists());
+
+ final URLConnection connection = unknownFile.getURL().openConnection();
+ try
+ {
+ connection.getInputStream();
+ fail();
+ }
+ catch (final IOException e)
+ {
+ assertSameMessage("vfs.provider/read-not-file.error", unknownFile, e);
+ }
+ assertEquals(-1, connection.getContentLength());
+ }
+
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/test/VerifyingFileSelector.java b/trunk/core/src/test/java/org/apache/commons/vfs2/test/VerifyingFileSelector.java
new file mode 100644
index 0000000..c34f9f2
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/test/VerifyingFileSelector.java
@@ -0,0 +1,150 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.test;
+
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSelectInfo;
+import org.apache.commons.vfs2.FileSelector;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.provider.AbstractFileObject;
+import org.apache.commons.vfs2.util.FileObjectUtils;
+import org.junit.Assert;
+
+/**
+ * A file selector that asserts that all files are visited, in the correct
+ * order.
+ */
+public class VerifyingFileSelector
+ extends Assert
+ implements FileSelector
+{
+ private final FileInfo rootFile;
+ private final List<FileObject> files = new ArrayList<FileObject>();
+
+ private FileInfo currentFolderInfo;
+ private FileObject currentFolder;
+ private Set<String> children;
+ private final List<Set<String>> stack = new ArrayList<Set<String>>();
+
+ public VerifyingFileSelector(final FileInfo fileInfo)
+ {
+ this.rootFile = fileInfo;
+ children = new HashSet<String>();
+ children.add(rootFile.baseName);
+ }
+
+ /**
+ * Determines if a file or folder should be selected.
+ */
+ @Override
+ public boolean includeFile(final FileSelectInfo fileInfo)
+ throws FileSystemException
+ {
+ final FileObject file = fileInfo.getFile();
+ if (file == currentFolder)
+ {
+ // Pop current folder
+ assertEquals(0, children.size());
+ currentFolder = currentFolder.getParent();
+ currentFolderInfo = currentFolderInfo.getParent();
+ children = stack.remove(0);
+ }
+
+ final String baseName = file.getName().getBaseName();
+
+ final FileInfo childInfo = getChild(baseName);
+ assertSame(childInfo.type, file.getType());
+
+ final boolean isChild = children.remove(baseName);
+ assertTrue(isChild);
+
+ files.add(file);
+ return true;
+ }
+
+ /**
+ * Determines whether a folder should be traversed.
+ */
+ @Override
+ public boolean traverseDescendents(final FileSelectInfo fileInfo)
+ throws FileSystemException
+ {
+ // Check that the given file is a folder
+ final FileObject folder = FileObjectUtils.getAbstractFileObject(fileInfo.getFile());
+ assertSame(FileType.FOLDER, folder.getType());
+ assertTrue(folder.isFolder());
+
+ // Locate the info for the folder
+ final String baseName = folder.getName().getBaseName();
+ if (currentFolder == null)
+ {
+ assertEquals(rootFile.baseName, baseName);
+ currentFolderInfo = rootFile;
+ }
+ else
+ {
+ AbstractFileObject parent = FileObjectUtils.getAbstractFileObject(folder.getParent());
+ assertSame(currentFolder, parent);
+
+ // Locate the info for the child, and make sure it is folder
+ currentFolderInfo = getChild(baseName);
+ assertSame(FileType.FOLDER, currentFolderInfo.type);
+ }
+
+ // Push the folder
+ stack.add(0, children);
+ children = new HashSet<String>(currentFolderInfo.children.keySet());
+ currentFolder = folder;
+
+ return true;
+ }
+
+ /**
+ * Finds a child of the current folder.
+ */
+ private FileInfo getChild(final String baseName)
+ {
+ if (currentFolderInfo == null)
+ {
+ assertEquals(rootFile.baseName, baseName);
+ return rootFile;
+ }
+ else
+ {
+ 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/trunk/core/src/test/java/org/apache/commons/vfs2/util/DelegatingFileSystemOptionsBuilderTest.java b/trunk/core/src/test/java/org/apache/commons/vfs2/util/DelegatingFileSystemOptionsBuilderTest.java
new file mode 100644
index 0000000..3db4849
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/util/DelegatingFileSystemOptionsBuilderTest.java
@@ -0,0 +1,136 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.util;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.io.File;
+import java.lang.reflect.InvocationTargetException;
+
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.impl.StandardFileSystemManager;
+import org.apache.commons.vfs2.provider.http.HttpFileSystemConfigBuilder;
+import org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder;
+import org.apache.commons.vfs2.provider.sftp.TrustEveryoneUserInfo;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+
+/**
+ * Some tests for the DelegatingFileSystemOptionsBuilder
+ */
+public class DelegatingFileSystemOptionsBuilderTest
+{
+ private StandardFileSystemManager fsm = null;
+
+ @Before
+ public void setUp() throws Exception
+ {
+
+ // get a full blown, fully functional manager
+ fsm = new StandardFileSystemManager();
+ fsm.init();
+ }
+
+
+ @After
+ public void tearDown() throws Exception
+ {
+ if (fsm != null)
+ {
+ fsm.close();
+ }
+ }
+
+ @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);
+ assertEquals("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());
+ }
+ }
+
+ @Test
+ public void testDelegatingBad() throws Throwable
+ {
+ final FileSystemOptions opts = new FileSystemOptions();
+ final DelegatingFileSystemOptionsBuilder delgate = new DelegatingFileSystemOptionsBuilder(fsm);
+
+ try
+ {
+ delgate.setConfigString(opts, "http", "proxyPort", "wrong_port");
+ fail();
+ }
+ catch (final FileSystemException e)
+ {
+ assertEquals(e.getCause().getClass(), InvocationTargetException.class);
+ assertEquals(((InvocationTargetException) e.getCause()).getTargetException().getClass(), NumberFormatException.class);
+ }
+
+ try
+ {
+ delgate.setConfigClass(opts, "sftp", "userinfo", String.class);
+ fail();
+ }
+ catch (final FileSystemException e)
+ {
+ assertEquals(e.getCode(), "vfs.provider/config-value-invalid.error");
+ }
+ }
+
+ private static String[] schemes = new String[]
+ {
+ "webdav", "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));
+ }
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/util/EncryptDecryptTest.java b/trunk/core/src/test/java/org/apache/commons/vfs2/util/EncryptDecryptTest.java
new file mode 100644
index 0000000..fab5979
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/util/EncryptDecryptTest.java
@@ -0,0 +1,42 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.util;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Test;
+
+/**
+ */
+public class EncryptDecryptTest
+{
+
+ @Test
+ public void testEncryptDecrypt() throws Exception
+ {
+ final String source = "Qryp2!t&tpR59";
+ final String expected = "914589F049CE3E8E3BB1A41BEAE12A9C";
+
+ final Cryptor cryptor = CryptorFactory.getCryptor();
+ final String encrypted = cryptor.encrypt(source);
+ assertEquals(expected, encrypted);
+
+ final String decrypted = cryptor.decrypt(encrypted);
+ assertEquals(source, decrypted);
+
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/util/FreeSocketPortUtil.java b/trunk/core/src/test/java/org/apache/commons/vfs2/util/FreeSocketPortUtil.java
new file mode 100644
index 0000000..2030560
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/util/FreeSocketPortUtil.java
@@ -0,0 +1,48 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.commons.vfs2.util;
+
+import java.io.IOException;
+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.
+ *
+ * @return a free local socket port.
+ * @throws IOException
+ */
+ public static int findFreeLocalPort() throws IOException
+ {
+ final ServerSocket server = new ServerSocket(0);
+ try
+ {
+ return server.getLocalPort();
+ } finally
+ {
+ server.close();
+ }
+ }
+}
diff --git a/trunk/core/src/test/java/org/apache/commons/vfs2/util/NHttpServer.java b/trunk/core/src/test/java/org/apache/commons/vfs2/util/NHttpServer.java
new file mode 100644
index 0000000..4147c1e
--- /dev/null
+++ b/trunk/core/src/test/java/org/apache/commons/vfs2/util/NHttpServer.java
@@ -0,0 +1,369 @@
+/*
+ * ====================================================================
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ * ====================================================================
+ *
+ * This software consists of voluntary contributions made by many
+ * individuals on behalf of the Apache Software Foundation. For more
+ * information on the Apache Software Foundation, please see
+ * <http://www.apache.org/>.
+ */
+package org.apache.commons.vfs2.util;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InterruptedIOException;
+import java.net.InetSocketAddress;
+import java.net.MalformedURLException;
+import java.net.URL;
+import java.net.URLDecoder;
+import java.security.KeyManagementException;
+import java.security.KeyStore;
+import java.security.KeyStoreException;
+import java.security.NoSuchAlgorithmException;
+import java.security.UnrecoverableKeyException;
+import java.security.cert.CertificateException;
+import java.util.Date;
+import java.util.Locale;
+import java.util.concurrent.Executors;
+
+import javax.net.ssl.KeyManager;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SSLContext;
+
+import org.apache.commons.httpclient.util.DateUtil;
+import org.apache.commons.io.IOUtils;
+import org.apache.http.HttpException;
+import org.apache.http.HttpHeaders;
+import org.apache.http.HttpRequest;
+import org.apache.http.HttpResponse;
+import org.apache.http.HttpResponseInterceptor;
+import org.apache.http.HttpStatus;
+import org.apache.http.MethodNotSupportedException;
+import org.apache.http.entity.ContentType;
+import org.apache.http.impl.DefaultConnectionReuseStrategy;
+import org.apache.http.impl.nio.DefaultHttpServerIODispatch;
+import org.apache.http.impl.nio.DefaultNHttpServerConnection;
+import org.apache.http.impl.nio.DefaultNHttpServerConnectionFactory;
+import org.apache.http.impl.nio.SSLNHttpServerConnectionFactory;
+import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
+import org.apache.http.nio.NHttpConnection;
+import org.apache.http.nio.NHttpConnectionFactory;
+import org.apache.http.nio.NHttpServerConnection;
+import org.apache.http.nio.entity.NFileEntity;
+import org.apache.http.nio.entity.NStringEntity;
+import org.apache.http.nio.protocol.BasicAsyncRequestConsumer;
+import org.apache.http.nio.protocol.BasicAsyncResponseProducer;
+import org.apache.http.nio.protocol.HttpAsyncExchange;
+import org.apache.http.nio.protocol.HttpAsyncRequestConsumer;
+import org.apache.http.nio.protocol.HttpAsyncRequestHandler;
+import org.apache.http.nio.protocol.HttpAsyncRequestHandlerRegistry;
+import org.apache.http.nio.protocol.HttpAsyncService;
+import org.apache.http.nio.reactor.IOEventDispatch;
+import org.apache.http.nio.reactor.IOReactorException;
+import org.apache.http.nio.reactor.ListeningIOReactor;
+import org.apache.http.params.CoreConnectionPNames;
+import org.apache.http.params.CoreProtocolPNames;
+import org.apache.http.params.HttpParams;
+import org.apache.http.params.SyncBasicHttpParams;
+import org.apache.http.protocol.ExecutionContext;
+import org.apache.http.protocol.HttpContext;
+import org.apache.http.protocol.HttpProcessor;
+import org.apache.http.protocol.ImmutableHttpProcessor;
+import org.apache.http.protocol.ResponseConnControl;
+import org.apache.http.protocol.ResponseContent;
+import org.apache.http.protocol.ResponseDate;
+import org.apache.http.protocol.ResponseServer;
+
+/**
+ * Adapted from org.apache.http.examples.nio.NHttpServer.
+ *
+ * <p>
+ * HTTP/1.1 file server based on the non-blocking I/O model and capable of direct channel (zero copy) data transfer.
+ * </p>
+ * <p>
+ * Please note the purpose of this application is demonstrate the usage of HttpCore APIs. It is NOT intended to
+ * demonstrate the most efficient way of building an HTTP server.
+ * </p>
+ *
+ * @version $Id$
+ * @since 2.1
+ */
+public class NHttpServer
+{
+
+ static class HttpFileHandler implements HttpAsyncRequestHandler<HttpRequest>
+ {
+
+ private final File docRoot;
+
+ public HttpFileHandler(final File docRoot)
+ {
+ super();
+ this.docRoot = docRoot;
+ }
+
+ @Override
+ public void handle(final HttpRequest request, final HttpAsyncExchange httpexchange, final HttpContext context)
+ throws HttpException, IOException
+ {
+ final HttpResponse response = httpexchange.getResponse();
+ this.handleInternal(request, response, context);
+ httpexchange.submitResponse(new BasicAsyncResponseProducer(response));
+ }
+
+ private void handleInternal(final HttpRequest request, final HttpResponse response, final HttpContext context)
+ throws HttpException, IOException
+ {
+
+ final String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
+ if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST"))
+ {
+ throw new MethodNotSupportedException(method + " method not supported");
+ }
+
+ final String target = request.getRequestLine().getUri();
+ final File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8"));
+ if (!file.exists())
+ {
+
+ response.setStatusCode(HttpStatus.SC_NOT_FOUND);
+ final NStringEntity entity = new NStringEntity("<html><body><h1>File" + file.getPath()
+ + " not found</h1></body></html>", ContentType.create("text/html", "UTF-8"));
+ response.setEntity(entity);
+ NHttpServer.debug("File " + file.getPath() + " not found");
+
+ } else if (!file.canRead())
+ {
+
+ response.setStatusCode(HttpStatus.SC_FORBIDDEN);
+ final NStringEntity entity = new NStringEntity("<html><body><h1>Access denied</h1></body></html>",
+ ContentType.create("text/html", "UTF-8"));
+ response.setEntity(entity);
+ NHttpServer.debug("Cannot read file " + file.getPath());
+
+ } else
+ {
+ final NHttpConnection conn = (NHttpConnection) context.getAttribute(ExecutionContext.HTTP_CONNECTION);
+ response.setStatusCode(HttpStatus.SC_OK);
+ final NFileEntity body = new NFileEntity(file, ContentType.create("text/html"));
+ response.setEntity(body);
+ if (!response.containsHeader(HttpHeaders.LAST_MODIFIED))
+ {
+ response.addHeader(HttpHeaders.LAST_MODIFIED, DateUtil.formatDate(new Date(file.lastModified())));
+ }
+ NHttpServer.debug(conn + ": serving file " + file.getPath());
+ }
+ }
+
+ @Override
+ public HttpAsyncRequestConsumer<HttpRequest> processRequest(final HttpRequest request, final HttpContext context)
+ {
+ // Buffer request content in memory for simplicity
+ return new BasicAsyncRequestConsumer();
+ }
+
+ }
+
+ static final boolean Debug = false;
+
+ private static void debug(final String s)
+ {
+ if (Debug)
+ {
+ System.out.println(s);
+ }
+ }
+
+ public static void main(final String[] args) throws Exception
+ {
+ new NHttpServer().run(Integer.valueOf(args[0]), new File(args[1]), 0);
+ }
+
+ volatile ListeningIOReactor ioReactor;
+
+ public boolean run(final int port, final File docRoot, final long waitMillis) throws IOReactorException,
+ InterruptedException
+ {
+ Executors.newSingleThreadExecutor().execute(new Runnable()
+ {
+ @Override
+ public void run()
+ {
+ try
+ {
+ NHttpServer.this.runBlock(port, docRoot);
+ } catch (final IOReactorException e)
+ {
+ throw new IllegalStateException(e);
+ } catch (final UnrecoverableKeyException e)
+ {
+ throw new IllegalStateException(e);
+ } catch (final KeyStoreException e)
+ {
+ throw new IllegalStateException(e);
+ } catch (final NoSuchAlgorithmException e)
+ {
+ throw new IllegalStateException(e);
+ } catch (final CertificateException e)
+ {
+ throw new IllegalStateException(e);
+ } catch (final IOException e)
+ {
+ throw new IllegalStateException(e);
+ } catch (final KeyManagementException e)
+ {
+ throw new IllegalStateException(e);
+ }
+ }
+ });
+ return this.waitForServerStartup(port, waitMillis);
+ }
+
+ public void runBlock(final int port, final File docRoot) throws KeyStoreException, NoSuchAlgorithmException,
+ CertificateException, IOException, UnrecoverableKeyException, KeyManagementException
+ {
+ if (docRoot == null)
+ {
+ throw new IllegalArgumentException("No doc root specified.");
+ }
+ // HTTP parameters for the server
+ final HttpParams params = new SyncBasicHttpParams();
+ params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
+ .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
+ .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
+ .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpTest/1.1");
+ // Create HTTP protocol processing chain
+ final HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[]
+ {
+ // Use standard server-side protocol interceptors
+ new ResponseDate(),
+ new ResponseServer(),
+ new ResponseContent(),
+ new ResponseConnControl() });
+ // Create request handler registry
+ final HttpAsyncRequestHandlerRegistry reqistry = new HttpAsyncRequestHandlerRegistry();
+ // Register the default handler for all URIs
+ reqistry.register("*", new HttpFileHandler(docRoot));
+ // Create server-side HTTP protocol handler
+ final HttpAsyncService protocolHandler = new HttpAsyncService(httpproc, new DefaultConnectionReuseStrategy(),
+ reqistry, params)
+ {
+
+ @Override
+ public void closed(final NHttpServerConnection conn)
+ {
+ NHttpServer.debug(conn + ": connection closed");
+ super.closed(conn);
+ }
+
+ @Override
+ public void connected(final NHttpServerConnection conn)
+ {
+ NHttpServer.debug(conn + ": connection open");
+ super.connected(conn);
+ }
+
+ };
+ // Create HTTP connection factory
+ NHttpConnectionFactory<DefaultNHttpServerConnection> connFactory;
+ if (port == 8443)
+ {
+ // Initialize SSL context
+ final ClassLoader cl = NHttpServer.class.getClassLoader();
+ final URL url = cl.getResource("my.keystore");
+ if (url == null)
+ {
+ NHttpServer.debug("Keystore not found");
+ System.exit(1);
+ }
+ final KeyStore keystore = KeyStore.getInstance("jks");
+ keystore.load(url.openStream(), "secret".toCharArray());
+ final KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
+ kmfactory.init(keystore, "secret".toCharArray());
+ final KeyManager[] keymanagers = kmfactory.getKeyManagers();
+ final SSLContext sslcontext = SSLContext.getInstance("TLS");
+ sslcontext.init(keymanagers, null, null);
+ connFactory = new SSLNHttpServerConnectionFactory(sslcontext, null, params);
+ } else
+ {
+ connFactory = new DefaultNHttpServerConnectionFactory(params);
+ }
+ // Create server-side I/O event dispatch
+ final IOEventDispatch ioEventDispatch = new DefaultHttpServerIODispatch(protocolHandler, connFactory);
+ // Create server-side I/O reactor
+ this.ioReactor = new DefaultListeningIOReactor();
+ try
+ {
+ // Listen of the given port
+ this.ioReactor.listen(new InetSocketAddress(port));
+ // Ready to go!
+ this.ioReactor.execute(ioEventDispatch);
+ } catch (final InterruptedIOException ex)
+ {
+ System.err.println("Interrupted");
+ } catch (final IOException e)
+ {
+ System.err.println("I/O error: " + e.getMessage());
+ }
+ NHttpServer.debug("Shutdown");
+ }
+
+ public void stop() throws IOException
+ {
+ if (this.ioReactor != null)
+ {
+ this.ioReactor.shutdown(2000);
+ }
+ }
+
+ private boolean waitForServerStartup(final int port, final long waitMillis) throws InterruptedException
+ {
+ final long endWait = System.currentTimeMillis() + waitMillis;
+ final String urlSpec = "http://localhost:" + port;
+ try
+ {
+ final URL url = new URL(urlSpec);
+ InputStream inputStream = null;
+ while (System.currentTimeMillis() < endWait && inputStream == null)
+ {
+ try
+ {
+ inputStream = url.openStream();
+ if (inputStream != null)
+ {
+ IOUtils.closeQuietly(inputStream);
+ return true;
+ }
+ } catch (final IOException e)
+ {
+ // ignore
+ // debug("While waiting: " + e);
+ // e.printStackTrace();
+ }
+ Thread.sleep(100);
+ }
+ } catch (final MalformedURLException e)
+ {
+ throw new IllegalStateException("Error in test code for URL " + urlSpec);
+ }
+ return false;
+ }
+
+}
diff --git a/trunk/core/src/test/resources/jcrweb.xml b/trunk/core/src/test/resources/jcrweb.xml
new file mode 100644
index 0000000..7124d45
--- /dev/null
+++ b/trunk/core/src/test/resources/jcrweb.xml
@@ -0,0 +1,186 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ -->
+
+<!-- Apache Commons VFS Note:
+ This file is from jackrabbit-standalone-1.6.5!WEB-INF/web.xml
+ Some servlets are removed or reconfigured to avoid cluttering directories.
+-->
+
+<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
+<web-app>
+ <display-name>Apache Jackrabbit</display-name>
+
+ <!-- ====================================================================== -->
+ <!-- R E P O S I T O R Y S E R V L E T -->
+ <!-- ====================================================================== -->
+ <servlet>
+ <servlet-name>Repository</servlet-name>
+ <servlet-class>org.apache.jackrabbit.j2ee.RepositoryAccessServlet</servlet-class>
+
+ <init-param>
+ <param-name>repository.context.attribute.name</param-name>
+ <param-value>javax.jcr.Repository</param-value>
+ </init-param>
+
+ <load-on-startup>2</load-on-startup>
+ </servlet>
+
+ <!-- ====================================================================== -->
+ <!-- W E B D A V S E R V L E T -->
+ <!-- ====================================================================== -->
+ <servlet>
+ <servlet-name>Webdav</servlet-name>
+ <description>
+ The webdav servlet that connects HTTP request to the repository.
+ </description>
+ <servlet-class>org.apache.jackrabbit.j2ee.SimpleWebdavServlet</servlet-class>
+
+ <init-param>
+ <param-name>resource-path-prefix</param-name>
+ <param-value>/repository</param-value>
+ <description>
+ defines the prefix for spooling resources out of the repository.
+ </description>
+ </init-param>
+ <init-param>
+ <param-name>resource-config</param-name>
+ <param-value>/WEB-INF/config.xml</param-value>
+ <description>
+ Defines various dav-resource configuration parameters.
+ </description>
+ </init-param>
+ <load-on-startup>3</load-on-startup>
+ </servlet>
+
+ <!-- ====================================================================== -->
+ <!-- W E B D A V S E R V E R S E R V L E T -->
+ <!-- ====================================================================== -->
+ <servlet>
+ <servlet-name>JCRWebdavServer</servlet-name>
+ <description>
+ The servlet used to remote JCR calls over HTTP.
+ </description>
+ <servlet-class>org.apache.jackrabbit.j2ee.JcrRemotingServlet</servlet-class>
+ <init-param>
+ <param-name>missing-auth-mapping</param-name>
+ <param-value></param-value>
+ <description>
+ Defines how a missing authorization header should be handled.
+ 1) If this init-param is missing, a 401 response is generated.
+ This is suiteable for clients (eg. webdav clients) for which
+ sending a proper authorization header is not possible if the
+ server never sent a 401.
+ 2) If this init-param is present with an empty value,
+ null-credentials are returned, thus forcing an null login
+ on the repository.
+ 3) If this init-param has a 'user:password' value, the respective
+ simple credentials are generated.
+ </description>
+ </init-param>
+ <!--
+ Optional parameter to define the value of the 'WWW-Authenticate' header
+ -->
+ <!--
+ <init-param>
+ <param-name>authenticate-header</param-name>
+ <param-value>Basic realm="Jackrabbit Webdav Server"</param-value>
+ <description>
+ Defines the value of the 'WWW-Authenticate' header.
+ </description>
+ </init-param>
+ -->
+ <init-param>
+ <param-name>resource-path-prefix</param-name>
+ <param-value>/server</param-value>
+ <description>
+ defines the prefix for spooling resources out of the repository.
+ </description>
+ </init-param>
+ <!--
+ Init parameters specific for JcrRemotingServlet
+ -->
+ <init-param>
+ <param-name>home</param-name>
+ <param-value>target/test/jackrabbit</param-value>
+ <description>JcrRemotingServlet: Optional home directory for JcrRemotingServlet temporary files (default: "jackrabbit")</description>
+ </init-param>
+ <init-param>
+ <param-name>rmi.enabled</param-name>
+ <param-value>false</param-value>
+ </init-param>
+ <!--
+ <init-param>
+ <param-name>temp-directory</param-name>
+ <param-value></param-value>
+ <description>JcrRemotingServlet: Optional temporary directory name (under home, default: "tmp")</description>
+ </init-param>
+ <init-param>
+ <param-name>batchread-config</param-name>
+ <param-value>/WEB-INF/batchread.properties</param-value>
+ <description>JcrRemotingServlet: Optional mapping from node type names to default depth.</description>
+ </init-param>
+ -->
+ <load-on-startup>5</load-on-startup>
+ </servlet>
+
+ <!-- ====================================================================== -->
+ <!-- R M I B I N D I N G S E R V L E T S -->
+ <!-- ====================================================================== -->
+<!-- <servlet>
+ <servlet-name>RMI</servlet-name>
+ <servlet-class>org.apache.jackrabbit.servlet.remote.RMIRemoteBindingServlet</servlet-class>
+ <init-param>
+ <param-name>url</param-name>
+ <param-value>//localhost/jackrabbit.repository</param-value>
+ </init-param>
+ <load-on-startup>6</load-on-startup>
+ </servlet>
+-->
+ <!-- ====================================================================== -->
+ <!-- S E R V L E T M A P P I N G -->
+ <!-- ====================================================================== -->
+ <servlet-mapping>
+ <servlet-name>Webdav</servlet-name>
+ <url-pattern>/repository/*</url-pattern>
+ </servlet-mapping>
+ <servlet-mapping>
+ <servlet-name>JCRWebdavServer</servlet-name>
+ <url-pattern>/server/*</url-pattern>
+ </servlet-mapping>
+<!-- <servlet-mapping>
+ <servlet-name>RMI</servlet-name>
+ <url-pattern>/rmi</url-pattern>
+ </servlet-mapping>-->
+
+ <!-- ====================================================================== -->
+ <!-- W E L C O M E F I L E S -->
+ <!-- ====================================================================== -->
+ <welcome-file-list>
+ <welcome-file>index.jsp</welcome-file>
+ </welcome-file-list>
+
+ <error-page>
+ <exception-type>org.apache.jackrabbit.j2ee.JcrApiNotFoundException</exception-type>
+ <location>/error/classpath.jsp</location>
+ </error-page>
+ <error-page>
+ <exception-type>javax.jcr.RepositoryException</exception-type>
+ <location>/error/repository.jsp</location>
+ </error-page>
+
+</web-app>
diff --git a/trunk/core/src/test/resources/log4j.properties b/trunk/core/src/test/resources/log4j.properties
new file mode 100644
index 0000000..11084db
--- /dev/null
+++ b/trunk/core/src/test/resources/log4j.properties
@@ -0,0 +1,36 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+# @version $Id: log4j.properties 27216 2011-09-14 02:34:00Z ggregory $
+
+log4j.rootLogger=ERROR, Console
+#log4j.rootLogger=WARN, Console
+#log4j.rootLogger=INFO, Console
+#log4j.rootLogger=DEBUG, Console
+
+###############################################################################
+# The console log
+#
+# Documentation: http://logging.apache.org/log4j/docs/api/org/apache/log4j/ConsoleAppender.html
+#
+# To enable this appender, add its name to the log4j.rootLogger list
+
+log4j.appender.Console=org.apache.log4j.ConsoleAppender
+log4j.appender.Console.ImmediateFlush=true
+log4j.appender.Console.Target=System.out
+log4j.appender.Console.layout=org.apache.log4j.PatternLayout
+log4j.appender.Console.layout.ConversionPattern=%d{ISO8601} [%t] %-5p: %m%n
diff --git a/trunk/core/src/test/resources/org.apache.ftpserver/users.properties b/trunk/core/src/test/resources/org.apache.ftpserver/users.properties
new file mode 100644
index 0000000..fadf36c
--- /dev/null
+++ b/trunk/core/src/test/resources/org.apache.ftpserver/users.properties
@@ -0,0 +1,43 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+# Password is "admin"
+ftpserver.user.admin.userpassword=21232F297A57A5A743894A0E4A801FC3
+ftpserver.user.admin.homedirectory=target/test-classes/test-data
+ftpserver.user.admin.enableflag=true
+ftpserver.user.admin.writepermission=true
+ftpserver.user.admin.maxloginnumber=0
+ftpserver.user.admin.maxloginperip=0
+ftpserver.user.admin.idletime=0
+ftpserver.user.admin.uploadrate=0
+ftpserver.user.admin.downloadrate=0
+
+ftpserver.user.anonymous.userpassword=
+ftpserver.user.anonymous.homedirectory=target/test-classes/test-data
+ftpserver.user.anonymous.enableflag=true
+ftpserver.user.anonymous.writepermission=false
+ftpserver.user.anonymous.maxloginnumber=20
+ftpserver.user.anonymous.maxloginperip=2
+ftpserver.user.anonymous.idletime=300
+ftpserver.user.anonymous.uploadrate=4800
+ftpserver.user.anonymous.downloadrate=4800
+
+# password is "test"
+ftpserver.user.test.userpassword=098f6bcd4621d373cade4e832627b4f6
+ftpserver.user.test.homedirectory=target/test-classes/test-data
+ftpserver.user.test.enableflag=true
+ftpserver.user.test.writepermission=true
diff --git a/trunk/core/src/test/resources/org.apache.ftpsserver/ftpserver.jks b/trunk/core/src/test/resources/org.apache.ftpsserver/ftpserver.jks
new file mode 100644
index 0000000..28f294b
--- /dev/null
+++ b/trunk/core/src/test/resources/org.apache.ftpsserver/ftpserver.jks
Binary files differ
diff --git a/trunk/core/src/test/resources/org.apache.ftpsserver/users.properties b/trunk/core/src/test/resources/org.apache.ftpsserver/users.properties
new file mode 100644
index 0000000..59fe696
--- /dev/null
+++ b/trunk/core/src/test/resources/org.apache.ftpsserver/users.properties
@@ -0,0 +1,43 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements. See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership. The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License. You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied. See the License for the
+# specific language governing permissions and limitations
+# under the License.
+
+# Password is "admin"
+ftpserver.user.admin.userpassword=21232F297A57A5A743894A0E4A801FC3
+ftpserver.user.admin.homedirectory=target/test-classes/test-data
+ftpserver.user.admin.enableflag=true
+ftpserver.user.admin.writepermission=true
+ftpserver.user.admin.maxloginnumber=0
+ftpserver.user.admin.maxloginperip=0
+ftpserver.user.admin.idletime=0
+ftpserver.user.admin.uploadrate=0
+ftpserver.user.admin.downloadrate=0
+
+ftpserver.user.anonymous.userpassword=
+ftpserver.user.anonymous.homedirectory=target/test-classes/test-data
+ftpserver.user.anonymous.enableflag=true
+ftpserver.user.anonymous.writepermission=false
+ftpserver.user.anonymous.maxloginnumber=20
+ftpserver.user.anonymous.maxloginperip=2
+ftpserver.user.anonymous.idletime=300
+ftpserver.user.anonymous.uploadrate=4800
+ftpserver.user.anonymous.downloadrate=4800
+
+# password is "test"
+ftpserver.user.test.userpassword=098f6bcd4621d373cade4e832627b4f6
+ftpserver.user.test.homedirectory=target/test-classes/test-data
+ftpserver.user.test.enableflag=true
+ftpserver.user.test.writepermission=true
diff --git a/trunk/core/src/test/resources/test-data/largefile.tar.gz b/trunk/core/src/test/resources/test-data/largefile.tar.gz
new file mode 100644
index 0000000..5bcc47a
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/largefile.tar.gz
Binary files differ
diff --git a/trunk/core/src/test/resources/test-data/nested.jar b/trunk/core/src/test/resources/test-data/nested.jar
new file mode 100644
index 0000000..c5bc269
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/nested.jar
Binary files differ
diff --git a/trunk/core/src/test/resources/test-data/nested.tar b/trunk/core/src/test/resources/test-data/nested.tar
new file mode 100644
index 0000000..ffc4089
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/nested.tar
Binary files differ
diff --git a/trunk/core/src/test/resources/test-data/nested.tbz2 b/trunk/core/src/test/resources/test-data/nested.tbz2
new file mode 100644
index 0000000..60ebcf0
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/nested.tbz2
Binary files differ
diff --git a/trunk/core/src/test/resources/test-data/nested.tgz b/trunk/core/src/test/resources/test-data/nested.tgz
new file mode 100644
index 0000000..cbbcb61
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/nested.tgz
Binary files differ
diff --git a/trunk/core/src/test/resources/test-data/nested.zip b/trunk/core/src/test/resources/test-data/nested.zip
new file mode 100644
index 0000000..d1c78f4
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/nested.zip
Binary files differ
diff --git a/trunk/core/src/test/resources/test-data/read-tests/dir1/file1.txt b/trunk/core/src/test/resources/test-data/read-tests/dir1/file1.txt
new file mode 100644
index 0000000..9ad7b1b
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/read-tests/dir1/file1.txt
@@ -0,0 +1 @@
+A test file.
\ No newline at end of file
diff --git a/trunk/core/src/test/resources/test-data/read-tests/dir1/file2.txt b/trunk/core/src/test/resources/test-data/read-tests/dir1/file2.txt
new file mode 100644
index 0000000..9ad7b1b
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/read-tests/dir1/file2.txt
@@ -0,0 +1 @@
+A test file.
\ No newline at end of file
diff --git a/trunk/core/src/test/resources/test-data/read-tests/dir1/file3.txt b/trunk/core/src/test/resources/test-data/read-tests/dir1/file3.txt
new file mode 100644
index 0000000..9ad7b1b
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/read-tests/dir1/file3.txt
@@ -0,0 +1 @@
+A test file.
\ No newline at end of file
diff --git a/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir1/file1.txt b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir1/file1.txt
new file mode 100644
index 0000000..9ad7b1b
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir1/file1.txt
@@ -0,0 +1 @@
+A test file.
\ No newline at end of file
diff --git a/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir1/file2.txt b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir1/file2.txt
new file mode 100644
index 0000000..9ad7b1b
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir1/file2.txt
@@ -0,0 +1 @@
+A test file.
\ No newline at end of file
diff --git a/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir1/file3.txt b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir1/file3.txt
new file mode 100644
index 0000000..9ad7b1b
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir1/file3.txt
@@ -0,0 +1 @@
+A test file.
\ No newline at end of file
diff --git a/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir2/file1.txt b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir2/file1.txt
new file mode 100644
index 0000000..9ad7b1b
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir2/file1.txt
@@ -0,0 +1 @@
+A test file.
\ No newline at end of file
diff --git a/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir2/file2.txt b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir2/file2.txt
new file mode 100644
index 0000000..9ad7b1b
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir2/file2.txt
@@ -0,0 +1 @@
+A test file.
\ No newline at end of file
diff --git a/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir2/file3.txt b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir2/file3.txt
new file mode 100644
index 0000000..9ad7b1b
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir2/file3.txt
@@ -0,0 +1 @@
+A test file.
\ No newline at end of file
diff --git a/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir3/file1.txt b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir3/file1.txt
new file mode 100644
index 0000000..9ad7b1b
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir3/file1.txt
@@ -0,0 +1 @@
+A test file.
\ No newline at end of file
diff --git a/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir3/file2.txt b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir3/file2.txt
new file mode 100644
index 0000000..9ad7b1b
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir3/file2.txt
@@ -0,0 +1 @@
+A test file.
\ No newline at end of file
diff --git a/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir3/file3.txt b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir3/file3.txt
new file mode 100644
index 0000000..9ad7b1b
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir3/file3.txt
@@ -0,0 +1 @@
+A test file.
\ No newline at end of file
diff --git a/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir4.jar/file1.txt b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir4.jar/file1.txt
new file mode 100644
index 0000000..9ad7b1b
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir4.jar/file1.txt
@@ -0,0 +1 @@
+A test file.
\ No newline at end of file
diff --git a/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir4.jar/file2.txt b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir4.jar/file2.txt
new file mode 100644
index 0000000..9ad7b1b
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir4.jar/file2.txt
@@ -0,0 +1 @@
+A test file.
\ No newline at end of file
diff --git a/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir4.jar/file3.txt b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir4.jar/file3.txt
new file mode 100644
index 0000000..9ad7b1b
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/read-tests/dir1/subdir4.jar/file3.txt
@@ -0,0 +1 @@
+A test file.
\ No newline at end of file
diff --git a/trunk/core/src/test/resources/test-data/read-tests/empty.txt b/trunk/core/src/test/resources/test-data/read-tests/empty.txt
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/read-tests/empty.txt
diff --git a/trunk/core/src/test/resources/test-data/read-tests/file space.txt b/trunk/core/src/test/resources/test-data/read-tests/file space.txt
new file mode 100644
index 0000000..af27ff4
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/read-tests/file space.txt
@@ -0,0 +1 @@
+This is a test file.
\ No newline at end of file
diff --git a/trunk/core/src/test/resources/test-data/read-tests/file%.txt b/trunk/core/src/test/resources/test-data/read-tests/file%.txt
new file mode 100644
index 0000000..af27ff4
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/read-tests/file%.txt
@@ -0,0 +1 @@
+This is a test file.
\ No newline at end of file
diff --git a/trunk/core/src/test/resources/test-data/read-tests/file1.txt b/trunk/core/src/test/resources/test-data/read-tests/file1.txt
new file mode 100644
index 0000000..af27ff4
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/read-tests/file1.txt
@@ -0,0 +1 @@
+This is a test file.
\ No newline at end of file
diff --git "a/trunk/core/src/test/resources/test-data/test-hash-\043test.txt" "b/trunk/core/src/test/resources/test-data/test-hash-\043test.txt"
new file mode 100644
index 0000000..8deb37d
--- /dev/null
+++ "b/trunk/core/src/test/resources/test-data/test-hash-\043test.txt"
@@ -0,0 +1 @@
+Test file for VFS-325: Bad handling of hashs (#) in file names when walking a file tree using findFiles().
\ No newline at end of file
diff --git a/trunk/core/src/test/resources/test-data/test.jar b/trunk/core/src/test/resources/test-data/test.jar
new file mode 100644
index 0000000..7ff1e6a
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/test.jar
Binary files differ
diff --git a/trunk/core/src/test/resources/test-data/test.mf b/trunk/core/src/test/resources/test-data/test.mf
new file mode 100644
index 0000000..e85d462
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/test.mf
@@ -0,0 +1,11 @@
+Manifest-Version: 1.0
+Specification-Title: SpecTitle
+Specification-Vendor: SpecVendor
+Specification-Version: 1.0
+Implementation-Title: ImplTitle
+Implementation-Vendor: ImplVendor
+Implementation-Version: 1.1
+Sealed: false
+
+Name: code/sealed/
+Sealed: true
diff --git a/trunk/core/src/test/resources/test-data/test.policy b/trunk/core/src/test/resources/test-data/test.policy
new file mode 100644
index 0000000..4c363a0
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/test.policy
@@ -0,0 +1,85 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements. See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership. The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License. You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied. See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+// Standard extensions get all permissions by default
+
+grant codeBase "file:${java.home}/lib/ext/*" {
+ permission java.security.AllPermission;
+};
+
+grant codeBase "file:${maven.home}/-" {
+ permission java.security.AllPermission;
+};
+
+grant codeBase "file:${maven.build.dest}" {
+ permission java.io.FilePermission "${user.dir}/vfs_cache/-", "read, write, delete";
+ permission java.io.FilePermission "${user.dir}/vfs_cache", "read, write, delete";
+ permission java.io.FilePermission "${user.dir}", "read";
+ permission java.net.NetPermission "specifyStreamHandler";
+};
+
+// default permissions granted to all domains
+
+grant {
+ permission java.io.FilePermission "${test.basedir}/write-tests", "read, write, delete";
+ permission java.io.FilePermission "${test.basedir}/write-tests/-", "read, write, delete";
+ permission java.io.FilePermission "${test.basedir}/-", "read";
+ permission java.io.FilePermission "${test.basedir}", "read";
+
+ //This is needed for the ClassLoader tests.
+ permission java.lang.RuntimePermission "createClassLoader";
+
+ // Allows any thread to stop itself using the java.lang.Thread.stop()
+ // method that takes no argument.
+ // Note that this permission is granted by default only to remain
+ // backwards compatible.
+ // It is strongly recommended that you either remove this permission
+ // from this policy file or further restrict it to code sources
+ // that you specify, because Thread.stop() is potentially unsafe.
+ // See "http://java.sun.com/notes" for more information.
+ permission java.lang.RuntimePermission "stopThread";
+
+ // allows anyone to listen on un-privileged ports
+ permission java.net.SocketPermission "localhost:1024-", "listen";
+
+ // "standard" properies that can be read by anyone
+
+ permission java.util.PropertyPermission "java.version", "read";
+ permission java.util.PropertyPermission "java.vendor", "read";
+ permission java.util.PropertyPermission "java.vendor.url", "read";
+ permission java.util.PropertyPermission "java.class.version", "read";
+ permission java.util.PropertyPermission "os.name", "read";
+ permission java.util.PropertyPermission "os.version", "read";
+ permission java.util.PropertyPermission "os.arch", "read";
+ permission java.util.PropertyPermission "file.separator", "read";
+ permission java.util.PropertyPermission "path.separator", "read";
+ permission java.util.PropertyPermission "line.separator", "read";
+
+ permission java.util.PropertyPermission "java.specification.version", "read";
+ permission java.util.PropertyPermission "java.specification.vendor", "read";
+ permission java.util.PropertyPermission "java.specification.name", "read";
+
+ permission java.util.PropertyPermission "java.vm.specification.version", "read";
+ permission java.util.PropertyPermission "java.vm.specification.vendor", "read";
+ permission java.util.PropertyPermission "java.vm.specification.name", "read";
+ permission java.util.PropertyPermission "java.vm.version", "read";
+ permission java.util.PropertyPermission "java.vm.vendor", "read";
+ permission java.util.PropertyPermission "java.vm.name", "read";
+ permission java.util.PropertyPermission "test.basedir", "read";
+ permission java.util.PropertyPermission "user.dir", "read";
+};
+
diff --git a/trunk/core/src/test/resources/test-data/test.tar b/trunk/core/src/test/resources/test-data/test.tar
new file mode 100644
index 0000000..ef82461
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/test.tar
Binary files differ
diff --git a/trunk/core/src/test/resources/test-data/test.tbz2 b/trunk/core/src/test/resources/test-data/test.tbz2
new file mode 100644
index 0000000..f7e2086
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/test.tbz2
Binary files differ
diff --git a/trunk/core/src/test/resources/test-data/test.tgz b/trunk/core/src/test/resources/test-data/test.tgz
new file mode 100644
index 0000000..579107d
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/test.tgz
Binary files differ
diff --git a/trunk/core/src/test/resources/test-data/test.zip b/trunk/core/src/test/resources/test-data/test.zip
new file mode 100644
index 0000000..3e5d4d9
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/test.zip
Binary files differ
diff --git a/trunk/core/src/test/resources/test-data/write-tests/dummy.txt b/trunk/core/src/test/resources/test-data/write-tests/dummy.txt
new file mode 100644
index 0000000..d7716a7
--- /dev/null
+++ b/trunk/core/src/test/resources/test-data/write-tests/dummy.txt
@@ -0,0 +1 @@
+dummy file to cause directory to be created.
\ No newline at end of file
diff --git a/trunk/dist/pom.xml b/trunk/dist/pom.xml
new file mode 100644
index 0000000..59a7902
--- /dev/null
+++ b/trunk/dist/pom.xml
@@ -0,0 +1,142 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements. See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to You under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+-->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <name>Apache Commons VFS Distribution</name>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2-distribution</artifactId>
+ <version>2.1</version>
+ <packaging>pom</packaging>
+ <description>Apache Commons VFS is a Virtual File System library - Distribution archives.</description>
+
+ <parent>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2-project</artifactId>
+ <version>2.1</version>
+ <relativePath>../</relativePath>
+ </parent>
+
+ <properties>
+ <!-- dist module contains no code and no checkstyle config -->
+ <checkstyle.skip>true</checkstyle.skip>
+ <vfs.parent.dir>${basedir}/..</vfs.parent.dir>
+ </properties>
+
+ <profiles>
+ <profile>
+ <id>release</id>
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2</artifactId>
+ <version>${project.version}</version>
+ <classifier>sources</classifier>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2</artifactId>
+ <version>${project.version}</version>
+ <classifier>javadoc</classifier>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2</artifactId>
+ <version>${project.version}</version>
+ <classifier>tests</classifier>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2</artifactId>
+ <version>${project.version}</version>
+ <classifier>test-sources</classifier>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2-examples</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2-examples</artifactId>
+ <version>${project.version}</version>
+ <classifier>sources</classifier>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2-examples</artifactId>
+ <version>${project.version}</version>
+ <classifier>javadoc</classifier>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <executions>
+ <!-- As the main Apache POM only builds source zip archives but
+ commons wants both zip and tar.gz and because this is configured
+ in the assembly, we need to use a specific assembly. That also allows
+ naming the final artifact as -src not -source-release.
+ -->
+ <execution>
+ <id>vfs-source-release-assembly</id>
+ <phase>package</phase>
+ <goals>
+ <goal>single</goal>
+ </goals>
+ <configuration>
+ <finalName>commons-vfs-${project.version}</finalName>
+ <descriptors>
+ <descriptor>src/assembly/src.xml</descriptor>
+ </descriptors>
+ <tarLongFileMode>gnu</tarLongFileMode>
+ </configuration>
+ </execution>
+ <execution>
+ <id>binary</id>
+ <configuration>
+ <finalName>commons-vfs-${project.version}</finalName>
+ <descriptors>
+ <descriptor>src/assembly/bin.xml</descriptor>
+ </descriptors>
+ <tarLongFileMode>gnu</tarLongFileMode>
+ </configuration>
+ <goals>
+ <goal>single</goal>
+ </goals>
+ <phase>package</phase>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ </profiles>
+</project>
diff --git a/trunk/dist/src/assembly/bin.xml b/trunk/dist/src/assembly/bin.xml
new file mode 100644
index 0000000..c175e60
--- /dev/null
+++ b/trunk/dist/src/assembly/bin.xml
@@ -0,0 +1,46 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+-->
+<assembly>
+ <id>bin</id>
+ <formats>
+ <format>tar.gz</format>
+ <format>zip</format>
+ </formats>
+ <includeSiteDirectory>false</includeSiteDirectory>
+
+ <dependencySets>
+ <dependencySet>
+ <includes>
+ <include>org.apache.commons:commons-vfs2</include>
+ <include>org.apache.commons:commons-vfs2-examples</include>
+ </includes>
+ <useProjectArtifact>false</useProjectArtifact>
+ </dependencySet>
+ </dependencySets>
+
+ <fileSets>
+ <fileSet>
+ <directory>..</directory>
+ <includes>
+ <include>LICENSE.txt</include>
+ <include>NOTICE.txt</include>
+ <include>RELEASE-NOTES.txt</include>
+ </includes>
+ </fileSet>
+ </fileSets>
+
+ </assembly>
diff --git a/trunk/dist/src/assembly/src.xml b/trunk/dist/src/assembly/src.xml
new file mode 100644
index 0000000..25c32a7
--- /dev/null
+++ b/trunk/dist/src/assembly/src.xml
@@ -0,0 +1,72 @@
+<?xml version='1.0' encoding='UTF-8'?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one
+ or more contributor license agreements. See the NOTICE file
+ distributed with this work for additional information
+ regarding copyright ownership. The ASF licenses this file
+ to you under the Apache License, Version 2.0 (the
+ "License"); you may not use this file except in compliance
+ with the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing,
+ software distributed under the License is distributed on an
+ "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ KIND, either express or implied. See the License for the
+ specific language governing permissions and limitations
+ under the License.
+-->
+
+<assembly>
+ <id>src</id>
+ <formats>
+ <format>zip</format>
+ <format>tar.gz</format>
+ </formats>
+ <fileSets>
+ <!-- main project directory structure -->
+ <fileSet>
+ <directory>..</directory>
+ <useDefaultExcludes>true</useDefaultExcludes>
+ <excludes>
+ <exclude>**/sandbox/**</exclude>
+ <!-- build output -->
+ <exclude>%regex[(?!((?!${project.build.directory}/)[^/]+/)*src/).*${project.build.directory}.*]</exclude>
+
+ <!-- NOTE: Most of the following excludes should not be required
+ if the standard release process is followed. This is because the
+ release plugin checks out project sources into a location like
+ target/checkout, then runs the build from there. The result is
+ a source-release archive that comes from a pretty clean directory
+ structure.
+
+ HOWEVER, if the release plugin is configured to run extra goals
+ or generate a project website, it's definitely possible that some
+ of these files will be present. So, it's safer to exclude them.
+ -->
+
+ <!-- IDEs -->
+ <exclude>%regex[(?!((?!${project.build.directory}/)[^/]+/)*src/)(.*/)?maven-eclipse\.xml]</exclude>
+ <exclude>%regex[(?!((?!${project.build.directory}/)[^/]+/)*src/)(.*/)?\.project]</exclude>
+ <exclude>%regex[(?!((?!${project.build.directory}/)[^/]+/)*src/)(.*/)?\.classpath]</exclude>
+ <exclude>%regex[(?!((?!${project.build.directory}/)[^/]+/)*src/)(.*/)?[^/]*\.iws]</exclude>
+ <exclude>%regex[(?!((?!${project.build.directory}/)[^/]+/)*src/)(.*/)?[^/]*\.ipr]</exclude>
+ <exclude>%regex[(?!((?!${project.build.directory}/)[^/]+/)*src/)(.*/)?[^/]*\.iml]</exclude>
+ <exclude>%regex[(?!((?!${project.build.directory}/)[^/]+/)*src/)(.*/)?\.idea(/.*)?]</exclude>
+ <exclude>%regex[(?!((?!${project.build.directory}/)[^/]+/)*src/)(.*/)?\.settings(/.*)?]</exclude>
+ <exclude>%regex[(?!((?!${project.build.directory}/)[^/]+/)*src/)(.*/)?\.externalToolBuilders(/.*)?]</exclude>
+ <exclude>%regex[(?!((?!${project.build.directory}/)[^/]+/)*src/)(.*/)?\.deployables(/.*)?]</exclude>
+ <exclude>%regex[(?!((?!${project.build.directory}/)[^/]+/)*src/)(.*/)?\.wtpmodules(/.*)?]</exclude>
+
+ <!-- misc -->
+ <exclude>%regex[(?!((?!${project.build.directory}/)[^/]+/)*src/)(.*/)?cobertura\.ser]</exclude>
+ <exclude>%regex[(?!((?!${project.build.directory}/)[^/]+/)*src/)(.*/)?doap_vfs\.rdf]</exclude>
+
+ <!-- release-plugin temp files -->
+ <exclude>%regex[(?!((?!${project.build.directory}/)[^/]+/)*src/)(.*/)?pom\.xml\.releaseBackup]</exclude>
+ <exclude>%regex[(?!((?!${project.build.directory}/)[^/]+/)*src/)(.*/)?release\.properties]</exclude>
+ </excludes>
+ </fileSet>
+ </fileSets>
+</assembly>
diff --git a/trunk/examples/pom.xml b/trunk/examples/pom.xml
new file mode 100644
index 0000000..bdb2777
--- /dev/null
+++ b/trunk/examples/pom.xml
@@ -0,0 +1,82 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+
+ <name>Apache Commons VFS Examples</name>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2-examples</artifactId>
+ <version>2.1</version>
+ <description>Apache Commons VFS is a Virtual File System library - Examples.</description>
+
+ <parent>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2-project</artifactId>
+ <version>2.1</version>
+ <relativePath>../</relativePath>
+ </parent>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>commons-net</groupId>
+ <artifactId>commons-net</artifactId>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-collections4</artifactId>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>commons-httpclient</groupId>
+ <artifactId>commons-httpclient</artifactId>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>com.jcraft</groupId>
+ <artifactId>jsch</artifactId>
+ <optional>true</optional>
+ </dependency>
+ </dependencies>
+
+ <properties>
+ <vfs.parent.dir>${basedir}/..</vfs.parent.dir>
+ </properties>
+
+ <build>
+ <resources>
+ <resource>
+ <directory>${vfs.parent.dir}</directory>
+ <targetPath>META-INF</targetPath>
+ <includes>
+ <include>NOTICE.txt</include>
+ <include>LICENSE.txt</include>
+ </includes>
+ </resource>
+ </resources>
+ </build>
+
+</project>
diff --git a/trunk/examples/src/main/java/org/apache/commons/vfs2/example/ChangeLastModificationTime.java b/trunk/examples/src/main/java/org/apache/commons/vfs2/example/ChangeLastModificationTime.java
new file mode 100644
index 0000000..a5ff9d8
--- /dev/null
+++ b/trunk/examples/src/main/java/org/apache/commons/vfs2/example/ChangeLastModificationTime.java
@@ -0,0 +1,47 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.example;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.VFS;
+
+/**
+ * Example to change the last modification time of the given file.
+ */
+public final class ChangeLastModificationTime
+{
+ private ChangeLastModificationTime()
+ {
+ /* main class not instantiated. */
+ }
+
+ public static void main(final String[] args) throws Exception
+ {
+ if (args.length == 0)
+ {
+ System.err.println("Please pass the name of a file as parameter.");
+ return;
+ }
+
+ final FileObject fo = VFS.getManager().resolveFile(args[0]);
+ final long setTo = System.currentTimeMillis();
+ System.err.println("set to: " + setTo);
+ fo.getContent().setLastModifiedTime(setTo);
+ System.err.println("after set: " + fo.getContent().getLastModifiedTime());
+ }
+
+}
diff --git a/trunk/examples/src/main/java/org/apache/commons/vfs2/example/Shell.java b/trunk/examples/src/main/java/org/apache/commons/vfs2/example/Shell.java
new file mode 100644
index 0000000..1484cc1
--- /dev/null
+++ b/trunk/examples/src/main/java/org/apache/commons/vfs2/example/Shell.java
@@ -0,0 +1,440 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.example;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStreamReader;
+import java.nio.charset.Charset;
+import java.text.DateFormat;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Date;
+import java.util.List;
+import java.util.StringTokenizer;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileContent;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.FileUtil;
+import org.apache.commons.vfs2.Selectors;
+import org.apache.commons.vfs2.VFS;
+import org.apache.commons.vfs2.operations.FileOperationProvider;
+
+/**
+ * A simple command-line shell for performing file operations.
+ * <p>
+ * See
+ * <a href="https://wiki.apache.org/commons/VfsExampleShell">Commons VFS Shell Examples</a>
+ * in Apache Commons Wiki.
+ */
+public final class Shell
+{
+ private final FileSystemManager mgr;
+ private FileObject cwd;
+ private final BufferedReader reader;
+
+ private Shell() throws IOException
+ {
+ mgr = VFS.getManager();
+ cwd = mgr.toFileObject(new File(System.getProperty("user.dir")));
+ reader = new BufferedReader(new InputStreamReader(System.in, Charset.defaultCharset()));
+ }
+
+ public static void main(final String[] args)
+ {
+ try
+ {
+ new Shell().go();
+ }
+ catch (final Exception e)
+ {
+ e.printStackTrace();
+ System.exit(1);
+ }
+ System.exit(0);
+ }
+
+ private void go() throws Exception
+ {
+ System.out.println("VFS Shell " + getVersion(Shell.class));
+ while (true)
+ {
+ final String[] cmd = nextCommand();
+ if (cmd == null)
+ {
+ return;
+ }
+ if (cmd.length == 0)
+ {
+ continue;
+ }
+ final String cmdName = cmd[0];
+ if (cmdName.equalsIgnoreCase("exit") || cmdName.equalsIgnoreCase("quit"))
+ {
+ return;
+ }
+ try
+ {
+ handleCommand(cmd);
+ }
+ catch (final Exception e)
+ {
+ System.err.println("Command failed:");
+ e.printStackTrace(System.err);
+ }
+ }
+ }
+
+ /**
+ * Handles a command.
+ */
+ private void handleCommand(final String[] cmd) throws Exception
+ {
+ final String cmdName = cmd[0];
+ if (cmdName.equalsIgnoreCase("cat"))
+ {
+ cat(cmd);
+ }
+ else if (cmdName.equalsIgnoreCase("cd"))
+ {
+ cd(cmd);
+ }
+ else if (cmdName.equalsIgnoreCase("cp"))
+ {
+ cp(cmd);
+ }
+ else if (cmdName.equalsIgnoreCase("help") || cmdName.equals("?"))
+ {
+ help();
+ }
+ else if (cmdName.equalsIgnoreCase("ls"))
+ {
+ ls(cmd);
+ }
+ else if (cmdName.equalsIgnoreCase("pwd"))
+ {
+ pwd();
+ }
+ else if (cmdName.equalsIgnoreCase("rm"))
+ {
+ rm(cmd);
+ }
+ else if (cmdName.equalsIgnoreCase("touch"))
+ {
+ touch(cmd);
+ }
+ else if (cmdName.equalsIgnoreCase("info"))
+ {
+ info(cmd);
+ }
+ else
+ {
+ System.err.println("Unknown command \"" + cmdName + "\" (Try 'help').");
+ }
+ }
+
+ private void info(String[] cmd) throws Exception
+ {
+ if (cmd.length > 1)
+ {
+ info(cmd[1]);
+ }
+ else
+ {
+ System.out.println("Default manager: \"" + mgr.getClass().getName() + "\" " +
+ "version " + getVersion(mgr.getClass()));
+ String[] schemes = mgr.getSchemes();
+ List<String> virtual = new ArrayList<String>();
+ List<String> physical = new ArrayList<String>();
+ for (int i = 0; i < schemes.length; i++)
+ {
+ Collection<Capability> caps = mgr.getProviderCapabilities(schemes[i]);
+ if (caps != null)
+ {
+ if (caps.contains(Capability.VIRTUAL) ||
+ caps.contains(Capability.COMPRESS) ||
+ caps.contains(Capability.DISPATCHER))
+ {
+ virtual.add(schemes[i]);
+ }
+ else
+ {
+ physical.add(schemes[i]);
+ }
+ }
+ }
+ if (!physical.isEmpty())
+ {
+ System.out.println(" Provider Schemes: " + physical);
+ }
+ if (!virtual.isEmpty())
+ {
+ System.out.println(" Virtual Schemes: " + virtual);
+ }
+ }
+ }
+
+ private void info(String scheme) throws Exception
+ {
+ System.out.println("Provider Info for scheme \"" + scheme + "\":");
+ Collection<Capability> caps;
+ caps = mgr.getProviderCapabilities(scheme);
+ if (caps != null && !caps.isEmpty())
+ {
+ System.out.println(" capabilities: " + caps);
+ }
+ FileOperationProvider[] ops = mgr.getOperationProviders(scheme);
+ if (ops != null && ops.length > 0)
+ {
+ System.out.println(" operations: " + ops);
+ }
+ }
+
+ /**
+ * Does a 'help' command.
+ */
+ private void help()
+ {
+ System.out.println("Commands:");
+ System.out.println("cat <file> Displays the contents of a file.");
+ System.out.println("cd [folder] Changes current folder.");
+ System.out.println("cp <src> <dest> Copies a file or folder.");
+ System.out.println("help Shows this message.");
+ System.out.println("info [scheme] Displays information about providers.");
+ System.out.println("ls [-R] [path] Lists contents of a file or folder.");
+ System.out.println("pwd Displays current folder.");
+ System.out.println("rm <path> Deletes a file or folder.");
+ System.out.println("touch <path> Sets the last-modified time of a file.");
+ System.out.println("exit, quit Exits this program.");
+ }
+
+ /**
+ * Does an 'rm' command.
+ */
+ private void rm(final String[] cmd) throws Exception
+ {
+ if (cmd.length < 2)
+ {
+ throw new Exception("USAGE: rm <path>");
+ }
+
+ final FileObject file = mgr.resolveFile(cwd, cmd[1]);
+ file.delete(Selectors.SELECT_SELF);
+ }
+
+ /**
+ * Does a 'cp' command.
+ */
+ private void cp(final String[] cmd) throws Exception
+ {
+ if (cmd.length < 3)
+ {
+ throw new Exception("USAGE: cp <src> <dest>");
+ }
+
+ final FileObject src = mgr.resolveFile(cwd, cmd[1]);
+ FileObject dest = mgr.resolveFile(cwd, cmd[2]);
+ if (dest.exists() && dest.getType() == FileType.FOLDER)
+ {
+ dest = dest.resolveFile(src.getName().getBaseName());
+ }
+
+ dest.copyFrom(src, Selectors.SELECT_ALL);
+ }
+
+ /**
+ * Does a 'cat' command.
+ */
+ private void cat(final String[] cmd) throws Exception
+ {
+ if (cmd.length < 2)
+ {
+ throw new Exception("USAGE: cat <path>");
+ }
+
+ // Locate the file
+ final FileObject file = mgr.resolveFile(cwd, cmd[1]);
+
+ // Dump the contents to System.out
+ FileUtil.writeContent(file, System.out);
+ System.out.println();
+ }
+
+ /**
+ * Does a 'pwd' command.
+ */
+ private void pwd()
+ {
+ System.out.println("Current folder is " + cwd.getName());
+ }
+
+ /**
+ * Does a 'cd' command.
+ * If the taget directory does not exist, a message is printed to <code>System.err</code>.
+ */
+ private void cd(final String[] cmd) throws Exception
+ {
+ final String path;
+ if (cmd.length > 1)
+ {
+ path = cmd[1];
+ }
+ else
+ {
+ path = System.getProperty("user.home");
+ }
+
+ // Locate and validate the folder
+ final FileObject tmp = mgr.resolveFile(cwd, path);
+ if (tmp.exists())
+ {
+ cwd = tmp;
+ }
+ else
+ {
+ System.out.println("Folder does not exist: " + tmp.getName());
+ }
+ System.out.println("Current folder is " + cwd.getName());
+ }
+
+ /**
+ * Does an 'ls' command.
+ */
+ private void ls(final String[] cmd) throws FileSystemException
+ {
+ int pos = 1;
+ final boolean recursive;
+ if (cmd.length > pos && cmd[pos].equals("-R"))
+ {
+ recursive = true;
+ pos++;
+ }
+ else
+ {
+ recursive = false;
+ }
+
+ final FileObject file;
+ if (cmd.length > pos)
+ {
+ file = mgr.resolveFile(cwd, cmd[pos]);
+ }
+ else
+ {
+ file = cwd;
+ }
+
+ if (file.getType() == FileType.FOLDER)
+ {
+ // List the contents
+ System.out.println("Contents of " + file.getName());
+ listChildren(file, recursive, "");
+ }
+ else
+ {
+ // Stat the file
+ System.out.println(file.getName());
+ final FileContent content = file.getContent();
+ System.out.println("Size: " + content.getSize() + " bytes.");
+ final DateFormat dateFormat = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
+ final String lastMod = dateFormat.format(new Date(content.getLastModifiedTime()));
+ System.out.println("Last modified: " + lastMod);
+ }
+ }
+
+ /**
+ * Does a 'touch' command.
+ */
+ private void touch(final String[] cmd) throws Exception
+ {
+ if (cmd.length < 2)
+ {
+ throw new Exception("USAGE: touch <path>");
+ }
+ final FileObject file = mgr.resolveFile(cwd, cmd[1]);
+ if (!file.exists())
+ {
+ file.createFile();
+ }
+ file.getContent().setLastModifiedTime(System.currentTimeMillis());
+ }
+
+ /**
+ * Lists the children of a folder.
+ */
+ private void listChildren(final FileObject dir,
+ final boolean recursive,
+ final String prefix)
+ throws FileSystemException
+ {
+ final FileObject[] children = dir.getChildren();
+ for (final FileObject child : children)
+ {
+ System.out.print(prefix);
+ System.out.print(child.getName().getBaseName());
+ if (child.getType() == FileType.FOLDER)
+ {
+ System.out.println("/");
+ if (recursive)
+ {
+ listChildren(child, recursive, prefix + " ");
+ }
+ }
+ else
+ {
+ System.out.println();
+ }
+ }
+ }
+
+ /**
+ * Returns the next command, split into tokens.
+ */
+ private String[] nextCommand() throws IOException
+ {
+ System.out.print("> ");
+ final String line = reader.readLine();
+ if (line == null)
+ {
+ return null;
+ }
+ final ArrayList<String> cmd = new ArrayList<String>();
+ final StringTokenizer tokens = new StringTokenizer(line);
+ while (tokens.hasMoreTokens())
+ {
+ cmd.add(tokens.nextToken());
+ }
+ return cmd.toArray(new String[cmd.size()]);
+ }
+
+ private static String getVersion(Class<?> cls)
+ {
+ try
+ {
+ return cls.getPackage().getImplementationVersion();
+ }
+ catch (Exception ignored)
+ {
+ return "N/A";
+ }
+ }
+}
diff --git a/trunk/examples/src/main/java/org/apache/commons/vfs2/example/ShowProperties.java b/trunk/examples/src/main/java/org/apache/commons/vfs2/example/ShowProperties.java
new file mode 100644
index 0000000..db095c8
--- /dev/null
+++ b/trunk/examples/src/main/java/org/apache/commons/vfs2/example/ShowProperties.java
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.example;
+
+import java.text.DateFormat;
+import java.util.Date;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.VFS;
+
+/**
+ * Example which prints all properties of the file passed as first parameter.
+ */
+public final class ShowProperties
+{
+ /** Maximum number of children to show. */
+ private static final int SHOW_MAX = 5;
+
+ private ShowProperties()
+ {
+ /* main class not instantiated. */
+ }
+
+ public static void main(final String[] args)
+ {
+ if (args.length == 0)
+ {
+ System.err.println("Please pass the name of a file as parameter.");
+ System.err.println("e.g. java org.apache.commons.vfs2.example.ShowProperties LICENSE.txt");
+ return;
+ }
+ for (final String arg : args)
+ {
+ try
+ {
+ final FileSystemManager mgr = VFS.getManager();
+ System.out.println();
+ System.out.println("Parsing: " + arg);
+ final FileObject file = mgr.resolveFile(arg);
+ System.out.println("URL: " + file.getURL());
+ System.out.println("getName(): " + file.getName());
+ System.out.println("BaseName: " + file.getName().getBaseName());
+ System.out.println("Extension: " + file.getName().getExtension());
+ System.out.println("Path: " + file.getName().getPath());
+ System.out.println("Scheme: " + file.getName().getScheme());
+ System.out.println("URI: " + file.getName().getURI());
+ System.out.println("Root URI: " + file.getName().getRootURI());
+ System.out.println("Parent: " + file.getName().getParent());
+ System.out.println("Type: " + file.getType());
+ System.out.println("Exists: " + file.exists());
+ System.out.println("Readable: " + file.isReadable());
+ System.out.println("Writeable: " + file.isWriteable());
+ System.out.println("Root path: " + file.getFileSystem().getRoot().getName().getPath());
+ if (file.exists())
+ {
+ if (file.getType().equals(FileType.FILE))
+ {
+ System.out.println("Size: " + file.getContent().getSize() + " bytes");
+ }
+ else if (file.getType().equals(FileType.FOLDER) && file.isReadable())
+ {
+ final FileObject[] children = file.getChildren();
+ System.out.println("Directory with " + children.length + " files");
+ for (int iterChildren = 0; iterChildren < children.length; iterChildren++)
+ {
+ System.out.println("#" + iterChildren + ": " + children[iterChildren].getName());
+ if (iterChildren > SHOW_MAX)
+ {
+ break;
+ }
+ }
+ }
+ System.out.println("Last modified: " + DateFormat.getInstance().format(
+ new Date(file.getContent().getLastModifiedTime())));
+ }
+ else
+ {
+ System.out.println("The file does not exist");
+ }
+ file.close();
+ }
+ catch (final FileSystemException ex)
+ {
+ ex.printStackTrace();
+ }
+ }
+ }
+
+}
+
diff --git a/trunk/examples/src/main/java/org/apache/commons/vfs2/example/package.html b/trunk/examples/src/main/java/org/apache/commons/vfs2/example/package.html
new file mode 100644
index 0000000..53385a2
--- /dev/null
+++ b/trunk/examples/src/main/java/org/apache/commons/vfs2/example/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>Apache Commons VFS Examples classes.</p>
+</body>
diff --git a/trunk/examples/src/main/java/org/apache/commons/vfs2/libcheck/FtpCheck.java b/trunk/examples/src/main/java/org/apache/commons/vfs2/libcheck/FtpCheck.java
new file mode 100644
index 0000000..542ae4f
--- /dev/null
+++ b/trunk/examples/src/main/java/org/apache/commons/vfs2/libcheck/FtpCheck.java
@@ -0,0 +1,97 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.libcheck;
+
+import java.io.OutputStream;
+import java.nio.charset.Charset;
+
+import org.apache.commons.net.ftp.FTPClient;
+import org.apache.commons.net.ftp.FTPFile;
+import org.apache.commons.net.ftp.FTPReply;
+
+/**
+ * Basic check for FTP.
+ */
+public final class FtpCheck
+{
+ private FtpCheck()
+ {
+ /* main class not instantiated. */
+ }
+
+ public static void main(final String[] args) throws Exception
+ {
+ if (args.length < 3)
+ {
+ throw new IllegalArgumentException("Usage: FtpCheck user pass host dir");
+ }
+ final String user = args[0];
+ final String pass = args[1];
+ final String host = args[2];
+ String dir = null;
+ if (args.length == 4)
+ {
+ dir = args[3];
+ }
+
+ final FTPClient client = new FTPClient();
+ client.connect(host);
+ final int reply = client.getReplyCode();
+ if (!FTPReply.isPositiveCompletion(reply))
+ {
+ throw new IllegalArgumentException("cant connect: " + reply);
+ }
+ if (!client.login(user, pass))
+ {
+ throw new IllegalArgumentException("login failed");
+ }
+ client.enterLocalPassiveMode();
+
+ final OutputStream os = client.storeFileStream(dir + "/test.txt");
+ if (os == null)
+ {
+ throw new IllegalStateException(client.getReplyString());
+ }
+ os.write("test".getBytes(Charset.defaultCharset()));
+ os.close();
+ client.completePendingCommand();
+
+ if (dir != null && !client.changeWorkingDirectory(dir))
+ {
+ throw new IllegalArgumentException("change dir to '" + dir + "' failed");
+ }
+
+ System.err.println("System: " + client.getSystemType());
+
+ final FTPFile[] files = client.listFiles();
+ for (int i = 0; i < files.length; i++)
+ {
+ final FTPFile file = files[i];
+ if (file == null)
+ {
+ System.err.println("#" + i + ": " + null);
+ }
+ else
+ {
+ System.err.println("#" + i + ": " + file.getRawListing());
+ System.err.println("#" + i + ": " + file.toString());
+ System.err.println("\t name:" + file.getName() + " type:" + file.getType());
+ }
+ }
+ client.disconnect();
+ }
+}
diff --git a/trunk/examples/src/main/java/org/apache/commons/vfs2/libcheck/SftpCheck.java b/trunk/examples/src/main/java/org/apache/commons/vfs2/libcheck/SftpCheck.java
new file mode 100644
index 0000000..7990a1b
--- /dev/null
+++ b/trunk/examples/src/main/java/org/apache/commons/vfs2/libcheck/SftpCheck.java
@@ -0,0 +1,104 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.libcheck;
+
+import java.util.Iterator;
+import java.util.Properties;
+import java.util.Vector;
+
+import com.jcraft.jsch.ChannelSftp;
+import com.jcraft.jsch.JSch;
+import com.jcraft.jsch.Session;
+import com.jcraft.jsch.UserInfo;
+
+/**
+ * Basic check for SFTP.
+ */
+public final class SftpCheck
+{
+ private SftpCheck()
+ {
+ /* main class not instantiated. */
+ }
+
+ public static void main(final String[] args) throws Exception
+ {
+ if (args.length != 4)
+ {
+ throw new IllegalArgumentException("Usage: SftpCheck user pass host dir");
+ }
+ final String user = args[0];
+ final String pass = args[1];
+ final String host = args[2];
+ final String dir = args[3];
+
+ final Properties props = new Properties();
+ props.setProperty("StrictHostKeyChecking", "false");
+ final JSch jsch = new JSch();
+ final Session session = jsch.getSession(user, host, 22);
+ session.setUserInfo(new UserInfo()
+ {
+ @Override
+ public String getPassphrase()
+ {
+ return null;
+ }
+
+ @Override
+ public String getPassword()
+ {
+ return null;
+ }
+
+ @Override
+ public boolean promptPassword(final String string)
+ {
+ return false;
+ }
+
+ @Override
+ public boolean promptPassphrase(final String string)
+ {
+ return false;
+ }
+
+ @Override
+ public boolean promptYesNo(final String string)
+ {
+ return true;
+ }
+
+ @Override
+ public void showMessage(final String string)
+ {
+ }
+ });
+ session.setPassword(pass);
+ session.connect();
+ final ChannelSftp chan = (ChannelSftp) session.openChannel("sftp");
+ chan.connect();
+ final Vector<?> list = chan.ls(dir);
+ final Iterator<?> iterList = list.iterator();
+ while (iterList.hasNext())
+ {
+ System.err.println(iterList.next());
+ }
+ System.err.println("done");
+ chan.disconnect();
+ session.disconnect();
+ }
+}
diff --git a/trunk/examples/src/main/java/org/apache/commons/vfs2/libcheck/package.html b/trunk/examples/src/main/java/org/apache/commons/vfs2/libcheck/package.html
new file mode 100644
index 0000000..553d5d2
--- /dev/null
+++ b/trunk/examples/src/main/java/org/apache/commons/vfs2/libcheck/package.html
@@ -0,0 +1,21 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<body>
+<p>Sample clients for commons-net.ftp and JSch libraries.</p>
+<p>The classes do not use the VFS library, but can be used to test the underlying
+libraries, if they can connect to a specified servicde.</p>
+</body>
diff --git a/trunk/examples/src/site/site.xml b/trunk/examples/src/site/site.xml
new file mode 100644
index 0000000..1da9b61
--- /dev/null
+++ b/trunk/examples/src/site/site.xml
@@ -0,0 +1,36 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<project name="Commons VFS">
+
+ <bannerRight>
+ <name>Commons VFS</name>
+ <src>../images/vfs-logo-white.png</src>
+ <href>../index.html</href>
+ </bannerRight>
+
+ <body>
+ <links>
+ <item name="Commons VFS Home" href="../index.html"/>
+ </links>
+
+ <!-- menues are inherited -->
+
+ <menu ref="reports"/>
+
+ </body>
+</project>
diff --git a/trunk/examples/src/site/xdoc/index.xml b/trunk/examples/src/site/xdoc/index.xml
new file mode 100644
index 0000000..144a63e
--- /dev/null
+++ b/trunk/examples/src/site/xdoc/index.xml
@@ -0,0 +1,104 @@
+<?xml version="1.0"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<document>
+ <properties>
+ <title>Apache Commons VFS Examples</title>
+ <author email="dev@commons.apache.org">Apache Commons Developers</author>
+ </properties>
+
+ <body>
+
+ <section name="About Apache Commons VFS Examples">
+ <p>
+ This example module contains sample
+ <a href="xref/index.html">source code</a> for learning how to use Apache
+ Commons VFS in the <code>org.apache.commons.vfs2.example</code> package.
+ </p>
+ <p>
+ The <code>org.apache.commons.vfs2.libcheck</code> package contains some Java
+ classes to exercise some of the functionality of the libraries (dependencies)
+ used by Apache Commons VFS. This is mainly for the maintainers of VFS providers.
+ </p>
+ </section>
+
+ <section name="Commons VFS Shell Example">
+
+ <p>
+ The Commons VFS Shell is an example for a command line shell.
+ It can be used to play with different providers and to verify
+ an installation.
+ </p>
+
+ <p>
+ Check out the page <a href="https://wiki.apache.org/commons/VfsExampleShell">VfsExampleShell</a>
+ on the Apache Commons Wiki for a number of examples. In particular you can use the <code>info</code>
+ command to list the schemes which are auto discovered by the <code>StandardFileSystemManager</code>.
+ </p>
+
+ <p>
+ The following examples assume an environment variable REP which points to a populated local Maven
+ repository. As an alternative you can <a href="../download.html">download</a> the required
+ <a href="../commons-vfs2/dependencies.html">dependencies</a> manually. (The commons-collection4
+ dependency is not needed for the VFS Shell as it does not use <code>LRUFilesCache</code>.) Because
+ of licensing restrictions the sandbox component must be
+ <a href="../commons-vfs2-sandbox/index.html">built locally</a> and then installed into the repository.
+ </p>
+
+ <subsection name="Starting VFS Shell on Linux/Unix">
+ <source><![CDATA[
+REP=~/.m2/repository
+LIB=$REP/commons-logging/commons-logging/1.2/commons-logging-1.2.jar
+LIB=$LIB:$REP/commons-net/commons-net/2.2/commons-net-2.2.jar
+# LIB=$LIB:$REP/org/apache/commons/commons-collections4/4.0/commons-collection-4.0.jar
+LIB=$LIB:$REP/commons-httpclient/commons-httpclient/3.1/commons-httpclient-3.1.jar:$REP/commons-codec/commons-codec/1.2/commons-codec-1.2.jar
+LIB=$LIB:$REP/com/jcraft/jsch/0.1.51/jsch-0.1.51.jar
+# next 3 lines are for webdav
+LIB=$LIB:$REP/org/apache/jackrabbit/jackrabbit-webdav/1.6.5/jackrabbit-webdav-1.6.5.jar
+LIB=$LIB:$REP/org/slf4j/slf4j-api/1.5.11/slf4j-api-1.5.11.jar:$REP/org/slf4j/slf4j-simple/1.5.3/slf4j-simple-1.5.3.jar
+LIB=$LIB:$REP/org/apache/jackrabbit/jackrabbit-jcr-commons/1.6.5/jackrabbit-jcr-commons-1.6.5.jar
+# LIB=$LIB:$REP/org/apache/commons/commons-vfs2-sandbox/2.1/commons-vfs2-sandbox-2.1.jar:$REP/jcifs/jcifs/0.8.3/jcifs-0.8.3.jar
+LIB=$LIB:$REP/org/apache/commons/commons-vfs2-examples/2.1/commons-vfs2-examples-2.1.jar
+LIB=$LIB:$REP/org/apache/commons/commons-vfs2/2.1/commons-vfs2-2.1.jar
+java -cp $LIB org.apache.commons.vfs2.example.Shell
+]]></source>
+ </subsection>
+
+ <subsection name="Starting VFS Shell on Windows">
+ <source><![CDATA[
+set REP=%USERPROFILE%\.m2\repository
+set LIB=%REP%\commons-logging\commons-logging\1.2\commons-logging-1.2.jar
+set LIB=%LIB%;%REP%\commons-net\commons-net\2.2\commons-net-2.2.jar
+REM # set LIB=%LIB%;%REP%\org\apache\commons\commons-collections4\4.0\commons-collection-4.0.jar
+set LIB=%LIB%;%REP%\commons-httpclient\commons-httpclient\3.1\commons-httpclient-3.1.jar;%REP%\commons-codec\commons-codec\1.2\commons-codec-1.2.jar
+set LIB=%LIB%;%REP%\com\jcraft\jsch\0.1.51\jsch-0.1.51.jar
+REM # next 3 lines are for webdav
+set LIB=%LIB%;%REP%\org\apache\jackrabbit\jackrabbit-webdav\1.6.5\jackrabbit-webdav-1.6.5.jar
+set LIB=%LIB%;%REP%\org\slf4j\slf4j-api\1.5.11\slf4j-api-1.5.11.jar;%REP%\org\slf4j\slf4j-simple\1.5.3\slf4j-simple-1.5.3.jar
+set LIB=%LIB%;%REP%\org\apache\jackrabbit\jackrabbit-jcr-commons\1.6.5\jackrabbit-jcr-commons-1.6.5.jar
+REM # set LIB=%LIB%;%REP%\org\apache\commons\commons-vfs2-sandbox\2.1\commons-vfs2-sandbox-2.1.jar;%REP%\jcifs\jcifs\0.8.3\jcifs-0.8.3.jar
+set LIB=%LIB%;%REP%\org\apache\commons\commons-vfs2-examples\2.1\commons-vfs2-examples-2.1.jar
+set LIB=%LIB%;%REP%\org\apache\commons\commons-vfs2\2.1\commons-vfs2-2.1.jar
+java -cp %LIB% org.apache.commons.vfs2.example.Shell
+]]></source>
+ </subsection>
+ </section>
+
+ </body>
+</document>
+
diff --git a/trunk/findbugs-exclude-filter.xml b/trunk/findbugs-exclude-filter.xml
new file mode 100644
index 0000000..873d353
--- /dev/null
+++ b/trunk/findbugs-exclude-filter.xml
@@ -0,0 +1,31 @@
+<?xml version="1.0" encoding="iso-8859-1"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<!-- ===================================================================== -->
+<!-- $Id$ -->
+<!-- ===================================================================== -->
+<FindBugsFilter>
+ <!-- Enable only high priority warnings -->
+ <Match>
+ <Priority value="2"/>
+ </Match>
+
+ <Match>
+ <Priority value="3"/>
+ </Match>
+</FindBugsFilter>
diff --git a/trunk/pom.xml b/trunk/pom.xml
new file mode 100644
index 0000000..d764705
--- /dev/null
+++ b/trunk/pom.xml
@@ -0,0 +1,566 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+ <parent>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-parent</artifactId>
+ <version>40</version>
+ </parent>
+
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2-project</artifactId>
+ <name>Apache Commons VFS</name>
+ <description>Apache Commons VFS is a Virtual File System library.</description>
+ <packaging>pom</packaging>
+ <version>2.1</version>
+
+ <url>http://commons.apache.org/proper/commons-vfs/</url>
+ <inceptionYear>2002</inceptionYear>
+
+ <modules>
+ <module>core</module>
+ <module>examples</module>
+ <module>dist</module>
+ </modules>
+
+ <issueManagement>
+ <system>jira</system>
+ <url>https://issues.apache.org/jira/browse/VFS</url>
+ </issueManagement>
+
+ <scm>
+ <connection>scm:svn:http://svn.apache.org/repos/asf/commons/proper/vfs/tags/commons-vfs2-project-2.1</connection>
+ <developerConnection>scm:svn:https://svn.apache.org/repos/asf/commons/proper/vfs/tags/commons-vfs2-project-2.1</developerConnection>
+ <url>http://svn.apache.org/viewvc/commons/proper/vfs/tags/commons-vfs2-project-2.1</url>
+ </scm>
+
+ <developers>
+ <developer>
+ <name>Adam Murdoch</name>
+ <id>adammurdoch</id>
+ <email>adammurdoch -at- apache.org</email>
+ <organization />
+ </developer>
+ <developer>
+ <name>James Strachan</name>
+ <id>jstrachan</id>
+ <email>jstrachan -at- apache.org</email>
+ <organization>SpiritSoft, Inc.</organization>
+ </developer>
+ <developer>
+ <name>Mario Ivankovits</name>
+ <id>imario</id>
+ <email>imario -at- apache.org</email>
+ <organization>OPS EDV Gmbh</organization>
+ </developer>
+ <developer>
+ <name>Rahul Akolkar</name>
+ <id>rahul</id>
+ <email>rahul -at- apache.org</email>
+ <organization>The Apache Software Foundation</organization>
+ </developer>
+ <developer>
+ <name>James Carman</name>
+ <id>jcarman</id>
+ <email>jcarman -at- apache.org</email>
+ <organization>The Apache Software Foundation</organization>
+ </developer>
+ <developer>
+ <name>Ralph Goers</name>
+ <id>rgoers</id>
+ <email>rgoers -at- apache.org</email>
+ <organization>Intuit</organization>
+ </developer>
+ <developer>
+ <name>Joerg Schaible</name>
+ <id>joehni</id>
+ <email>joehni -at- apache.org</email>
+ </developer>
+ <developer>
+ <name>Gary D. Gregory</name>
+ <id>ggregory</id>
+ <email>ggregory -at- apache.org</email>
+ <url>http://www.garygregory.com</url>
+ <timezone>-5</timezone>
+ </developer>
+ <developer>
+ <name>Bernd Eckenfels</name>
+ <id>ecki</id>
+ <email>ecki -at- apache.org</email>
+ <url>http://bernd.eckenfels.net</url>
+ <timezone>+1</timezone>
+ </developer>
+ </developers>
+
+ <contributors>
+ <contributor>
+ <name>Rami Ojares</name>
+ <email>rami.ojares -at- elisa.fi</email>
+ </contributor>
+ <contributor>
+ <name>Anthony Goubard</name>
+ <email>adagoubard -at- chello.nl</email>
+ </contributor>
+ <contributor>
+ <name>Christopher Ottley</name>
+ <email>xknight -at- users.sourceforge.net</email>
+ </contributor>
+ <contributor>
+ <name>Dave Marion</name>
+ <email>dlmarion -at- apache.org</email>
+ </contributor>
+ <contributor>
+ <name>Scott Bjerstedt</name>
+ <email>jcottbjer -at- gmail.com</email>
+ </contributor>
+ <contributor>
+ <name>Jose Juan Montiel</name>
+ <email>josejuan.montiel -at- gmail.com</email>
+ </contributor>
+ </contributors>
+
+ <properties>
+ <commons.encoding>UTF-8</commons.encoding>
+
+ <maven.compiler.source>1.6</maven.compiler.source>
+ <maven.compiler.target>1.6</maven.compiler.target>
+
+ <!-- bare ID without major version or commons- prefix -->
+ <commons.componentid>vfs</commons.componentid>
+ <commons.binary.suffix />
+ <commons.jira.id>VFS</commons.jira.id>
+ <commons.jira.pid>12310495</commons.jira.pid>
+ <commons.scmPubUrl>https://svn.apache.org/repos/infra/websites/production/commons/content/proper/commons-vfs</commons.scmPubUrl>
+
+ <commons.release.version>2.1</commons.release.version>
+ <!--<commons.rc.version>RC1</commons.rc.version> -->
+ <commons.release.name>commons-vfs-${commons.release.version}</commons.release.name>
+ <commons.release.desc>(requires Java 1.6+)</commons.release.desc>
+
+ <commons.release.2.version>2.0</commons.release.2.version>
+ <commons.release.2.name>commons-vfs-2.0</commons.release.2.name>
+ <commons.release.2.desc>(requires Java 1.5+)</commons.release.2.desc>
+ <commons.release.2.binary.suffix />
+
+ <vfs.parent.dir>${basedir}</vfs.parent.dir>
+ <version.checkstyle>2.13</version.checkstyle>
+ <!-- make sure bundle plugin has dependency informations for 'optional' -->
+ <commons.osgi.excludeDependencies />
+ </properties>
+
+ <build>
+ <resources>
+ <resource>
+ <directory>${basedir}/osgi</directory>
+ <targetPath>osgi</targetPath>
+ <includes>
+ <include>MANIFEST.MF</include>
+ </includes>
+ </resource>
+ </resources>
+
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-antrun-plugin</artifactId>
+ <executions>
+ <execution>
+ <id>vfs-jar-manifest</id>
+ <phase>generate-sources</phase>
+ <goals>
+ <goal>run</goal>
+ </goals>
+ <configuration>
+ <target>
+ <mkdir dir="${project.build.directory}/osgi" />
+ <touch file="${project.build.directory}/osgi/MANIFEST.MF" />
+ </target>
+ </configuration>
+ </execution>
+ <execution>
+ <id>javadoc.resources</id>
+ <phase>generate-sources</phase>
+ <goals>
+ <goal>run</goal>
+ </goals>
+ <configuration>
+ <target>
+ <copy todir="${project.build.directory}/apidocs/META-INF">
+ <fileset dir="${vfs.parent.dir}">
+ <include name="LICENSE.txt" />
+ <include name="NOTICE.txt" />
+ </fileset>
+ </copy>
+ </target>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <version>${version.checkstyle}</version>
+ <!-- Keep build/reporting in sync -->
+ <configuration>
+ <!--<propertiesLocation>${vfs.parent.dir}/checkstyle.properties</propertiesLocation> -->
+ <configLocation>${vfs.parent.dir}/checkstyle.xml</configLocation>
+ <suppressionsLocation>${vfs.parent.dir}/checkstyle-suppressions.xml</suppressionsLocation>
+ <enableRulesSummary>false</enableRulesSummary>
+ <propertyExpansion>basedir=${basedir}</propertyExpansion>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.rat</groupId>
+ <artifactId>apache-rat-plugin</artifactId>
+ <version>${commons.rat.version}</version>
+ <!-- Should agree with config in reporting section -->
+ <configuration>
+ <excludes combine.children="append">
+ <!-- trivial test data text files -->
+ <exclude>src/test/resources/test-data/**/*.txt</exclude>
+ <exclude>src/test/resources/test-data/test.mf</exclude>
+ <!-- implicite exclude does not work if sandbox profile is not activated -->
+ <exclude>sandbox/**</exclude>
+ </excludes>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+
+ <reporting>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.rat</groupId>
+ <artifactId>apache-rat-plugin</artifactId>
+ <version>${commons.rat.version}</version>
+ <!-- Should agree with config in build section -->
+ <configuration>
+ <excludes combine.children="append">
+ <!-- trivial test data text files -->
+ <exclude>src/test/resources/test-data/**/*.txt</exclude>
+ <exclude>src/test/resources/test-data/test.mf</exclude>
+ <!-- implicit exclude does not work if sandbox profile is not activated -->
+ <exclude>sandbox/**</exclude>
+ </excludes>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <version>${version.checkstyle}</version>
+ <!-- Keep build/reporting in sync -->
+ <configuration>
+ <!--<propertiesLocation>${vfs.parent.dir}/checkstyle.properties</propertiesLocation> -->
+ <configLocation>${vfs.parent.dir}/checkstyle.xml</configLocation>
+ <suppressionsLocation>${vfs.parent.dir}/checkstyle-suppressions.xml</suppressionsLocation>
+ <enableRulesSummary>false</enableRulesSummary>
+ <propertyExpansion>basedir=${basedir}</propertyExpansion>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ <version>${commons.javadoc.version}</version>
+ <configuration>
+ <tags>
+ <tag>
+ <name>todo</name>
+ <!-- todo tag for all places -->
+ <placement>a</placement>
+ <head>To Do:</head>
+ </tag>
+ </tags>
+ <aggregate>true</aggregate>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>findbugs-maven-plugin</artifactId>
+ <!-- commons-parent defines version 2.5.x or 3.x depending on JDK active. -->
+ <version>${commons.findbugs.version}</version>
+ <configuration>
+ <threshold>Normal</threshold>
+ <effort>Default</effort>
+ <excludeFilterFile>${vfs.parent.dir}/findbugs-exclude-filter.xml</excludeFilterFile>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-pmd-plugin</artifactId>
+ <version>3.3</version>
+ <configuration>
+ <targetJdk>${maven.compiler.target}</targetJdk>
+ <aggregate>true</aggregate>
+ </configuration>
+ </plugin>
+ <!-- cobertura breaks because it cannot parse annotations in methods. -->
+ <!--
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>cobertura-maven-plugin</artifactId>
+ <version>${commons.cobertura.version}</version>
+ </plugin>
+ -->
+ <!-- javancss breaks because it cannot parse annotations in methods. -->
+ <!--
+ <plugin>
+ <groupId>org.codehaus.mojo</groupId>
+ <artifactId>javancss-maven-plugin</artifactId>
+ <version>2.0</version>
+ </plugin>
+ -->
+ </plugins>
+ </reporting>
+
+ <dependencyManagement>
+ <dependencies>
+ <!-- artifacts of project, versions managed by release-plugin -->
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2</artifactId>
+ <version>${project.version}</version>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2-sandbox</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2-examples</artifactId>
+ <version>${project.version}</version>
+ </dependency>
+
+ <!-- 3rd party dependencies -->
+ <dependency>
+ <groupId>commons-logging</groupId>
+ <artifactId>commons-logging</artifactId>
+ <version>1.2</version>
+ </dependency>
+ <dependency>
+ <groupId>commons-net</groupId>
+ <artifactId>commons-net</artifactId>
+ <version>3.4</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-collections4</artifactId>
+ <version>4.1</version>
+ </dependency>
+ <dependency>
+ <groupId>commons-httpclient</groupId>
+ <artifactId>commons-httpclient</artifactId>
+ <version>3.1</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-compress</artifactId>
+ <version>1.10</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.jackrabbit</groupId>
+ <artifactId>jackrabbit-webdav</artifactId>
+ <version>1.6.5</version>
+ </dependency>
+ <dependency>
+ <groupId>ant</groupId>
+ <artifactId>ant</artifactId>
+ <version>1.6.5</version>
+ </dependency>
+ <dependency>
+ <groupId>com.jcraft</groupId>
+ <artifactId>jsch</artifactId>
+ <version>0.1.53</version>
+ </dependency>
+ <dependency>
+ <groupId>jcifs</groupId>
+ <artifactId>jcifs</artifactId>
+ <version>0.8.3</version>
+ </dependency>
+ <dependency>
+ <groupId>javax.mail</groupId>
+ <artifactId>mail</artifactId>
+ <version>1.4.7</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-common</artifactId>
+ <version>2.6.0</version>
+ <exclusions>
+ <exclusion>
+ <groupId>*</groupId>
+ <artifactId>*</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-hdfs</artifactId>
+ <version>2.6.0</version>
+ <exclusions>
+ <exclusion>
+ <groupId>*</groupId>
+ <artifactId>*</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+
+ <!-- Testing -->
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.12</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ <version>3.4</version>
+ </dependency>
+ <!-- Test FTP with Apache FTP Server (MINA) -->
+ <dependency>
+ <groupId>org.apache.ftpserver</groupId>
+ <artifactId>ftpserver-core</artifactId>
+ <version>1.0.6</version>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-api</artifactId>
+ <version>1.5.11</version>
+ </dependency>
+ <dependency>
+ <groupId>org.slf4j</groupId>
+ <artifactId>jcl-over-slf4j</artifactId>
+ <version>1.5.11</version>
+ </dependency>
+ <!-- Test SFTP with Apache SSHd Server (MINA) -->
+ <dependency>
+ <groupId>org.apache.sshd</groupId>
+ <artifactId>sshd-core</artifactId>
+ <version>0.8.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.mina</groupId>
+ <artifactId>mina-core</artifactId>
+ <version>2.0.7</version>
+ </dependency>
+ <dependency>
+ <groupId>org.bouncycastle</groupId>
+ <artifactId>bcprov-jdk16</artifactId>
+ <version>1.46</version>
+ </dependency>
+ <dependency>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ <version>2.5</version>
+ </dependency>
+ <!-- Test HTTP with Apache HttpComponent Core -->
+ <dependency>
+ <groupId>org.apache.httpcomponents</groupId>
+ <artifactId>httpcore-nio</artifactId>
+ <version>4.3.2</version>
+ </dependency>
+ <!-- Test WebDAV with Apache Jackrabbit -->
+ <dependency>
+ <groupId>org.apache.jackrabbit</groupId>
+ <artifactId>jackrabbit-standalone</artifactId>
+ <version>1.6.5</version>
+ <exclusions>
+ <exclusion>
+ <!-- provides everything inlined. -->
+ <groupId>*</groupId>
+ <artifactId>*</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <!-- HDFS test dependencies -->
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-common</artifactId>
+ <version>2.6.0</version>
+ <type>test-jar</type>
+ <exclusions>
+ <exclusion>
+ <!-- jackrabbit-standalone provides one, too -->
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.hadoop</groupId>
+ <artifactId>hadoop-hdfs</artifactId>
+ <version>2.6.0</version>
+ <type>test-jar</type>
+ </dependency>
+ <dependency>
+ <groupId>javax.ws.rs</groupId>
+ <artifactId>jsr311-api</artifactId>
+ <version>1.1.1</version>
+ </dependency>
+ </dependencies>
+ </dependencyManagement>
+
+ <distributionManagement>
+ <site>
+ <id>commons.site</id>
+ <name>Apache Commons Site</name>
+ <url>scm:svn:${commons.scmPubUrl}</url>
+ </site>
+ </distributionManagement>
+
+ <!-- Releasing VFS as a multi-module build with binary artifacts is somewhat painful. This profile hooks into the commons-parent
+ and the apache-pom to get the build done and then uses the assembly to package it up. -->
+ <profiles>
+ <profile>
+ <id>include-sandbox</id>
+ <modules>
+ <module>sandbox</module>
+ </modules>
+ </profile>
+ <profile>
+ <id>release</id>
+ <build>
+ <plugins>
+ <plugin>
+ <artifactId>maven-assembly-plugin</artifactId>
+ <executions>
+ <!-- Don't build the archives here. They are constructed in the dist project -->
+ <execution>
+ <configuration>
+ <skipAssembly>true</skipAssembly>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+
+ </profiles>
+
+</project>
diff --git a/trunk/sandbox/pom.xml b/trunk/sandbox/pom.xml
new file mode 100644
index 0000000..c988f7e
--- /dev/null
+++ b/trunk/sandbox/pom.xml
@@ -0,0 +1,159 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ -->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+ <modelVersion>4.0.0</modelVersion>
+
+ <name>Apache Commons VFS Sandbox</name>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2-sandbox</artifactId>
+ <version>2.1-SNAPSHOT</version>
+ <description>Apache Commons VFS is a Virtual File System library - Sandbox.</description>
+
+ <parent>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2-project</artifactId>
+ <version>2.1-SNAPSHOT</version>
+ <relativePath>../</relativePath>
+ </parent>
+
+ <dependencies>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2</artifactId>
+ </dependency>
+
+ <dependency>
+ <groupId>commons-logging</groupId>
+ <artifactId>commons-logging</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>jcifs</groupId>
+ <artifactId>jcifs</artifactId>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>commons-httpclient</groupId>
+ <artifactId>commons-httpclient</artifactId>
+ <optional>true</optional>
+ </dependency>
+ <dependency>
+ <groupId>javax.mail</groupId>
+ <artifactId>mail</artifactId>
+ <optional>true</optional>
+ </dependency>
+
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-vfs2</artifactId>
+ <type>test-jar</type>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>commons-io</groupId>
+ <artifactId>commons-io</artifactId>
+ <scope>test</scope>
+ </dependency>
+ </dependencies>
+
+ <properties>
+ <commons.componentid>vfs-sandbox</commons.componentid>
+ <vfs.parent.dir>${basedir}/..</vfs.parent.dir>
+ </properties>
+
+ <build>
+ <resources>
+ <resource>
+ <directory>${project.basedir}/src/main/resources</directory>
+ </resource>
+ <resource>
+ <directory>${vfs.parent.dir}</directory>
+ <targetPath>META-INF</targetPath>
+ <includes>
+ <include>NOTICE.txt</include>
+ <include>LICENSE.txt</include>
+ </includes>
+ </resource>
+ </resources>
+ <!-- include NOTICE/LICENSE in generated test jar -->
+ <testResources>
+ <testResource>
+ <directory>${vfs.parent.dir}</directory>
+ <targetPath>META-INF</targetPath>
+ <includes>
+ <include>NOTICE.txt</include>
+ <include>LICENSE.txt</include>
+ </includes>
+ </testResource>
+ </testResources>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <executions>
+ <execution>
+ <goals>
+ <goal>test-jar</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <!-- surfire do not honor suite(), see MSUREFIRE-131 why our tests wont work with maven 2 -->
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <systemPropertyVariables>
+ <test.basedir>../core/target/test-classes/test-data</test.basedir>
+ <test.basedir.res>test-data</test.basedir.res>
+ </systemPropertyVariables>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ <profiles>
+ <profile>
+ <id>smb</id>
+ <activation>
+ <activeByDefault>false</activeByDefault>
+ </activation>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <configuration>
+ <systemPropertyVariables>
+ <test.basedir>../core/target/test-classes/test-data</test.basedir>
+ <test.basedir.res>test-data</test.basedir.res>
+ <test.smb.uri>${test.smb.uri}</test.smb.uri>
+ </systemPropertyVariables>
+ </configuration>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ </profiles>
+</project>
diff --git a/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/mime/MimeAttributesMap.java b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/mime/MimeAttributesMap.java
new file mode 100644
index 0000000..3d336c0
--- /dev/null
+++ b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/mime/MimeAttributesMap.java
@@ -0,0 +1,269 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.mime;
+
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.TreeMap;
+
+import javax.mail.Address;
+import javax.mail.Header;
+import javax.mail.MessagingException;
+import javax.mail.Part;
+import javax.mail.internet.MimeMessage;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+/**
+ * A map which tries to allow access to the various aspects of the mail.
+ */
+public class MimeAttributesMap implements Map<String, Object>
+{
+ private static final String OBJECT_PREFIX = "obj.";
+
+ private final Log log = LogFactory.getLog(MimeAttributesMap.class);
+ private final Part part;
+ private final Map<String, Method> mimeMessageGetters = new TreeMap<String, Method>();
+
+ private Map<String, Object> backingMap;
+
+
+ public MimeAttributesMap(final Part part)
+ {
+ this.part = part;
+ addMimeMessageMethod(part.getClass().getMethods());
+ addMimeMessageMethod(part.getClass().getDeclaredMethods());
+ }
+
+ private void addMimeMessageMethod(final Method[] methods)
+ {
+ for (final Method method : methods)
+ {
+ if (!Modifier.isPublic(method.getModifiers()))
+ {
+ continue;
+ }
+ if (method.getParameterTypes().length > 0)
+ {
+ continue;
+ }
+
+ if (method.getName().startsWith("get"))
+ {
+ mimeMessageGetters.put(method.getName().substring(3), method);
+ }
+ else if (method.getName().startsWith("is"))
+ {
+ mimeMessageGetters.put(method.getName().substring(2), method);
+ }
+ }
+ }
+
+ private Map<String, Object> getMap()
+ {
+ if (backingMap == null)
+ {
+ backingMap = createMap();
+ }
+
+ return backingMap;
+ }
+
+ private Map<String, Object> createMap()
+ {
+ // Object is either a String, or a List of Strings
+ final Map<String, Object> ret = new TreeMap<String, Object>();
+
+ Enumeration<Header> headers;
+ try
+ {
+ @SuppressWarnings("unchecked") // Javadoc say Part returns Header
+ final
+ Enumeration<Header> allHeaders = part.getAllHeaders();
+ headers = allHeaders;
+ }
+ catch (final MessagingException e)
+ {
+ throw new RuntimeException(e);
+ }
+
+ // add all headers
+ while (headers.hasMoreElements())
+ {
+ final Header header = headers.nextElement();
+ final String headerName = header.getName();
+
+ final Object values = ret.get(headerName);
+
+ if (values == null)
+ {
+ ret.put(headerName, header.getValue());
+ }
+ else if (values instanceof String)
+ {
+ final ArrayList<String> newValues = new ArrayList<String>();
+ newValues.add((String) values);
+ newValues.add(header.getValue());
+ ret.put(headerName, newValues);
+ }
+ else if (values instanceof List)
+ {
+ @SuppressWarnings("unchecked") // we only add Strings to the Lists
+ final
+ List<String> list = (List<String>) values;
+ list.add(header.getValue());
+ }
+ }
+
+ // add all simple get/is results (with obj. prefix)
+ final Iterator<Entry<String, Method>> iterEntries = mimeMessageGetters.entrySet().iterator();
+ while (iterEntries.hasNext())
+ {
+ final Map.Entry<String, Method> entry = iterEntries.next();
+ final String name = entry.getKey();
+ final Method method = entry.getValue();
+
+ try
+ {
+ final Object value = method.invoke(part);
+ ret.put(OBJECT_PREFIX + name, value);
+ }
+ catch (final IllegalAccessException e)
+ {
+ log.debug(e.getLocalizedMessage(), e);
+ }
+ catch (final InvocationTargetException e)
+ {
+ log.debug(e.getLocalizedMessage(), e);
+ }
+ }
+
+ // add extended fields (with obj. prefix too)
+ if (part instanceof MimeMessage)
+ {
+ final MimeMessage message = (MimeMessage) part;
+ try
+ {
+ final Address[] address = message.getRecipients(MimeMessage.RecipientType.BCC);
+ ret.put(OBJECT_PREFIX + "Recipients.BCC", address);
+ }
+ catch (final MessagingException e)
+ {
+ log.debug(e.getLocalizedMessage(), e);
+ }
+ try
+ {
+ final Address[] address = message.getRecipients(MimeMessage.RecipientType.CC);
+ ret.put(OBJECT_PREFIX + "Recipients.CC", address);
+ }
+ catch (final MessagingException e)
+ {
+ log.debug(e.getLocalizedMessage(), e);
+ }
+ try
+ {
+ final Address[] address = message.getRecipients(MimeMessage.RecipientType.TO);
+ ret.put(OBJECT_PREFIX + "Recipients.TO", address);
+ }
+ catch (final MessagingException e)
+ {
+ log.debug(e.getLocalizedMessage(), e);
+ }
+ try
+ {
+ final Address[] address = message.getRecipients(MimeMessage.RecipientType.NEWSGROUPS);
+ ret.put(OBJECT_PREFIX + "Recipients.NEWSGROUPS", address);
+ }
+ catch (final MessagingException e)
+ {
+ log.debug(e.getLocalizedMessage(), e);
+ }
+ }
+
+ return ret;
+ }
+
+ public int size()
+ {
+ return getMap().size();
+ }
+
+ public boolean isEmpty()
+ {
+ return getMap().size() < 1;
+ }
+
+ public boolean containsKey(final Object key)
+ {
+ return getMap().containsKey(key);
+ }
+
+ public boolean containsValue(final Object value)
+ {
+ return getMap().containsValue(value);
+ }
+
+ public Object get(final Object key)
+ {
+ return getMap().get(key);
+ }
+
+ public Object put(final String key, final Object value)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public Object remove(final Object key)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public void putAll(final Map<? extends String, ? extends Object> t)
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public void clear()
+ {
+ throw new UnsupportedOperationException();
+ }
+
+ public Set<String> keySet()
+ {
+ return Collections.unmodifiableSet(getMap().keySet());
+ }
+
+ public Collection<Object> values()
+ {
+ return Collections.unmodifiableCollection(getMap().values());
+ }
+
+ public Set<Entry<String, Object>> entrySet()
+ {
+ return Collections.unmodifiableSet(getMap().entrySet());
+ }
+}
diff --git a/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/mime/MimeFileContentInfoFactory.java b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/mime/MimeFileContentInfoFactory.java
new file mode 100644
index 0000000..de3643f
--- /dev/null
+++ b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/mime/MimeFileContentInfoFactory.java
@@ -0,0 +1,94 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.mime;
+
+import javax.mail.MessagingException;
+import javax.mail.Part;
+import javax.mail.internet.ContentType;
+
+import org.apache.commons.vfs2.FileContent;
+import org.apache.commons.vfs2.FileContentInfo;
+import org.apache.commons.vfs2.FileContentInfoFactory;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.impl.DefaultFileContentInfo;
+
+/**
+ * Get access to the content info stuff for mime objects.
+ */
+public class MimeFileContentInfoFactory implements FileContentInfoFactory
+{
+ public FileContentInfo create(final FileContent fileContent) throws FileSystemException
+ {
+ final MimeFileObject mimeFile = (MimeFileObject) fileContent.getFile();
+ final Part part = mimeFile.getPart();
+
+ String contentTypeString = null;
+ String charset = null;
+
+ try
+ {
+ // special handling for multipart
+ if (mimeFile.isMultipart())
+ {
+ // get the original content type, but ...
+ contentTypeString = part.getContentType();
+
+ // .... we deliver the preamble instead of an inupt string
+ // the preamble will be delivered in UTF-8 - fixed
+ charset = MimeFileSystem.PREAMBLE_CHARSET;
+ }
+ }
+ catch (final MessagingException e)
+ {
+ throw new FileSystemException(e);
+ }
+
+ if (contentTypeString == null)
+ {
+ // normal message ... get the content type
+ try
+ {
+ contentTypeString = part.getContentType();
+ }
+ catch (final MessagingException e)
+ {
+ throw new FileSystemException(e);
+ }
+ }
+
+ ContentType contentType;
+ try
+ {
+ contentType = new ContentType(contentTypeString);
+ }
+ catch (final MessagingException e)
+ {
+ throw new FileSystemException(e);
+ }
+
+ if (charset == null)
+ {
+ // charset might already be set by the multipart message stuff, else
+ // extract it from the contentType now
+ charset = contentType.getParameter("charset"); // NON-NLS
+ }
+
+ return new DefaultFileContentInfo(
+ contentType.getBaseType(),
+ charset);
+ }
+}
diff --git a/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/mime/MimeFileObject.java b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/mime/MimeFileObject.java
new file mode 100644
index 0000000..f9dade3
--- /dev/null
+++ b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/mime/MimeFileObject.java
@@ -0,0 +1,309 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.mime;
+
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.Enumeration;
+import java.util.List;
+import java.util.Map;
+
+import javax.mail.Header;
+import javax.mail.Message;
+import javax.mail.MessagingException;
+import javax.mail.Multipart;
+import javax.mail.Part;
+import javax.mail.internet.MimeMultipart;
+
+import org.apache.commons.vfs2.FileContentInfoFactory;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.NameScope;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileObject;
+import org.apache.commons.vfs2.provider.UriParser;
+import org.apache.commons.vfs2.util.FileObjectUtils;
+
+/**
+ * A part of a MIME message.
+ */
+public class MimeFileObject
+ extends AbstractFileObject<MimeFileSystem>
+ implements FileObject
+{
+ private Part part;
+ private Map<String, Object> attributeMap;
+
+ protected MimeFileObject(final AbstractFileName name,
+ final Part part,
+ final MimeFileSystem fileSystem) throws FileSystemException
+ {
+ super(name, fileSystem);
+ setPart(part);
+ }
+ /**
+ * Attaches this file object to its file resource.
+ */
+ @Override
+ protected void doAttach() throws Exception
+ {
+ if (part == null)
+ {
+ if (!getName().equals(getFileSystem().getRootName()))
+ {
+ final MimeFileObject foParent = (MimeFileObject) FileObjectUtils.getAbstractFileObject(getParent());
+ setPart(foParent.findPart(getName().getBaseName()));
+ return;
+ }
+
+ setPart(((MimeFileSystem) getFileSystem()).createCommunicationLink());
+ }
+ }
+
+ private Part findPart(final String partName) throws Exception
+ {
+ if (getType() == FileType.IMAGINARY)
+ {
+ // not existent
+ return null;
+ }
+
+ if (isMultipart())
+ {
+ final Multipart multipart = (Multipart) part.getContent();
+ if (partName.startsWith(MimeFileSystem.NULL_BP_NAME))
+ {
+ final int partNumber = Integer.parseInt(partName.substring(MimeFileSystem.NULL_BP_NAME.length()), 10);
+ if (partNumber < 0 || partNumber + 1 > multipart.getCount())
+ {
+ // non existent
+ return null;
+ }
+
+ return multipart.getBodyPart(partNumber);
+ }
+
+ for (int i = 0; i < multipart.getCount(); i++)
+ {
+ final Part childPart = multipart.getBodyPart(i);
+ if (partName.equals(childPart.getFileName()))
+ {
+ return childPart;
+ }
+ }
+ }
+
+ return null;
+ }
+
+ @Override
+ protected void doDetach() throws Exception
+ {
+ }
+
+ /**
+ * Determines the type of the file, returns null if the file does not
+ * exist.
+ */
+ @Override
+ protected FileType doGetType() throws Exception
+ {
+ if (part == null)
+ {
+ return FileType.IMAGINARY;
+ }
+
+ if (isMultipart())
+ {
+ // we cant have children ...
+ return FileType.FILE_OR_FOLDER;
+ }
+
+ return FileType.FILE;
+ }
+
+ @Override
+ protected String[] doListChildren() throws Exception
+ {
+ return null;
+ }
+
+ /**
+ * Lists the children of the file. Is only called if {@link #doGetType}
+ * returns {@link org.apache.commons.vfs2.FileType#FOLDER}.
+ */
+ @Override
+ protected FileObject[] doListChildrenResolved() throws Exception
+ {
+ if (part == null)
+ {
+ return null;
+ }
+
+ final List<MimeFileObject> vfs = new ArrayList<MimeFileObject>();
+ if (isMultipart())
+ {
+ final Object container = part.getContent();
+ if (container instanceof Multipart)
+ {
+ final Multipart multipart = (Multipart) container;
+
+ for (int i = 0; i < multipart.getCount(); i++)
+ {
+ final Part part = multipart.getBodyPart(i);
+
+ String filename = UriParser.encode(part.getFileName());
+ if (filename == null)
+ {
+ filename = MimeFileSystem.NULL_BP_NAME + i;
+ }
+
+ final MimeFileObject fo = (MimeFileObject) FileObjectUtils.getAbstractFileObject(
+ getFileSystem().resolveFile(
+ getFileSystem().getFileSystemManager().resolveName(getName(),
+ filename,
+ NameScope.CHILD)));
+ fo.setPart(part);
+ vfs.add(fo);
+ }
+ }
+ }
+
+ return vfs.toArray(new MimeFileObject[vfs.size()]);
+ }
+
+ private void setPart(final Part part)
+ {
+ this.part = part;
+ this.attributeMap = null;
+ }
+
+ /**
+ * Returns the size of the file content (in bytes).
+ */
+ @Override
+ protected long doGetContentSize() throws Exception
+ {
+ return part.getSize();
+ }
+
+ /**
+ * Returns the last modified time of this file.
+ */
+ @Override
+ protected long doGetLastModifiedTime()
+ throws Exception
+ {
+ final Message mm = getMessage();
+ if (mm == null)
+ {
+ return -1;
+ }
+ if (mm.getSentDate() != null)
+ {
+ return mm.getSentDate().getTime();
+ }
+ if (mm.getReceivedDate() != null)
+ {
+ mm.getReceivedDate();
+ }
+ return 0;
+ }
+
+ private Message getMessage() throws FileSystemException
+ {
+ if (part instanceof Message)
+ {
+ return (Message) part;
+ }
+
+ return ((MimeFileObject) FileObjectUtils.getAbstractFileObject(getParent())).getMessage();
+ }
+
+ /**
+ * Creates an input stream to read the file content from.
+ */
+ @Override
+ protected InputStream doGetInputStream() throws Exception
+ {
+ if (isMultipart())
+ {
+ // deliver the preamble as the only content
+
+ final String preamble = ((MimeMultipart) part.getContent()).getPreamble();
+ if (preamble == null)
+ {
+ return new ByteArrayInputStream(new byte[]{});
+ }
+ return new ByteArrayInputStream(preamble.getBytes(MimeFileSystem.PREAMBLE_CHARSET));
+ }
+
+ return part.getInputStream();
+ }
+
+ boolean isMultipart() throws MessagingException
+ {
+ return part.getContentType() != null && part.getContentType().startsWith("multipart/");
+ }
+
+ @Override
+ protected FileContentInfoFactory getFileContentInfoFactory()
+ {
+ return new MimeFileContentInfoFactory();
+ }
+
+ protected Part getPart()
+ {
+ return part;
+ }
+
+ /**
+ * Returns all headers of this part.
+ * <p>
+ * The map key is a java.lang.String and the value is a:
+ * <ul>
+ * <li>{@code java.lang.Strings} for single entries or a</li>
+ * <li>{@code java.utils.List<java.lang.Strings>} for entries with multiple values</li>
+ * </ul>
+ */
+ @Override
+ protected Map<String, Object> doGetAttributes() throws Exception
+ {
+ if (attributeMap == null)
+ {
+ if (part != null)
+ {
+ attributeMap = new MimeAttributesMap(part);
+ }
+ else
+ {
+ attributeMap = Collections.emptyMap();
+ }
+ }
+
+ return attributeMap;
+ }
+
+ @SuppressWarnings("unchecked") // Javadoc says Part returns Header
+ protected Enumeration<Header> getAllHeaders() throws MessagingException
+ {
+ return part.getAllHeaders();
+ }
+}
diff --git a/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/mime/MimeFileProvider.java b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/mime/MimeFileProvider.java
new file mode 100644
index 0000000..295664b
--- /dev/null
+++ b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/mime/MimeFileProvider.java
@@ -0,0 +1,74 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.mime;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.provider.AbstractLayeredFileProvider;
+import org.apache.commons.vfs2.provider.FileProvider;
+import org.apache.commons.vfs2.provider.LayeredFileName;
+
+/**
+ * A provider for MIME Message.
+ */
+public class MimeFileProvider
+ extends AbstractLayeredFileProvider
+ implements FileProvider
+{
+ static final Collection<Capability> capabilities =
+ Collections.unmodifiableCollection(Arrays.asList(new Capability[]
+ {
+ Capability.GET_TYPE,
+ Capability.GET_LAST_MODIFIED,
+ Capability.LIST_CHILDREN,
+ Capability.READ_CONTENT,
+ Capability.URI,
+ Capability.ATTRIBUTES
+ }));
+
+ public MimeFileProvider()
+ {
+ super();
+ }
+
+ /**
+ * Creates the filesystem.
+ */
+ @Override
+ protected FileSystem doCreateFileSystem(final String scheme, final FileObject file,
+ final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ final FileName name =
+ new LayeredFileName(scheme, file.getName(), FileName.ROOT_PATH, FileType.FOLDER);
+ return new MimeFileSystem(name, file, fileSystemOptions);
+ }
+
+ public Collection<Capability> getCapabilities()
+ {
+ return capabilities;
+ }
+}
diff --git a/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/mime/MimeFileSystem.java b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/mime/MimeFileSystem.java
new file mode 100644
index 0000000..960688a
--- /dev/null
+++ b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/mime/MimeFileSystem.java
@@ -0,0 +1,131 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.mime;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.Collection;
+
+import javax.mail.MessagingException;
+import javax.mail.Part;
+import javax.mail.internet.MimeMessage;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileSystem;
+import org.apache.commons.vfs2.util.SharedRandomContentInputStream;
+
+/**
+ * An MIME file system.
+ */
+public class MimeFileSystem
+ extends AbstractFileSystem
+{
+ static final String NULL_BP_NAME = "_body_part_";
+ static final String CONTENT_NAME = "_content";
+ static final String PREAMBLE_CHARSET = "UTF-8";
+
+ private final Log log = LogFactory.getLog(MimeFileSystem.class);
+
+ private InputStream mimeStream = null;
+
+ protected MimeFileSystem(final FileName rootName, final FileObject parentLayer,
+ final FileSystemOptions fileSystemOptions)
+ {
+ super(rootName, parentLayer, fileSystemOptions);
+ }
+
+ /**
+ * Creates a file object.
+ */
+ @Override
+ protected FileObject createFile(final AbstractFileName name) throws FileSystemException
+ {
+ return new MimeFileObject(name, null, this);
+ }
+
+ /**
+ * Returns the capabilities of this file system.
+ */
+ @Override
+ protected void addCapabilities(final Collection<Capability> caps)
+ {
+ caps.addAll(MimeFileProvider.capabilities);
+ }
+
+
+ @Override
+ protected void doCloseCommunicationLink()
+ {
+ try
+ {
+ if (mimeStream == null)
+ {
+ return;
+ }
+
+ closeMimeStream();
+ mimeStream = null;
+ }
+ catch (final IOException e)
+ {
+ log.warn(e.getLocalizedMessage(), e);
+ }
+ }
+
+ private void closeMimeStream() throws IOException
+ {
+ if (mimeStream instanceof SharedRandomContentInputStream)
+ {
+ ((SharedRandomContentInputStream) mimeStream).closeAll();
+ }
+ else
+ {
+ mimeStream.close();
+ }
+ }
+
+ public Part createCommunicationLink() throws IOException, MessagingException
+ {
+ if (mimeStream != null)
+ {
+ closeMimeStream();
+ }
+
+ final FileObject parentLayer = getParentLayer();
+ if (!parentLayer.exists())
+ {
+ return null;
+ }
+
+ if (parentLayer.getFileSystem().hasCapability(Capability.RANDOM_ACCESS_READ))
+ {
+ mimeStream = new SharedRandomContentInputStream(parentLayer);
+ }
+ else
+ {
+ mimeStream = getParentLayer().getContent().getInputStream();
+ }
+ return new MimeMessage(null, mimeStream);
+ }
+}
diff --git a/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/mime/package.html b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/mime/package.html
new file mode 100644
index 0000000..2b20633
--- /dev/null
+++ b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/mime/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ -->
+<body>
+<p>VFS (Sandbox) Mime File Provider.</p>
+</body>
diff --git a/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/smb/SmbFileName.java b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/smb/SmbFileName.java
new file mode 100644
index 0000000..96dfb7d
--- /dev/null
+++ b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/smb/SmbFileName.java
@@ -0,0 +1,147 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.smb;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.provider.GenericFileName;
+
+/**
+ * An SMB URI. Adds a share name to the generic URI.
+ */
+public class SmbFileName extends GenericFileName
+{
+ private static final int DEFAULT_PORT = 139;
+
+ private final String share;
+ private final String domain;
+ private String uriWithoutAuth;
+
+ protected SmbFileName(
+ final String scheme,
+ final String hostName,
+ final int port,
+ final String userName,
+ final String password,
+ final String domain,
+ final String share,
+ final String path,
+ final FileType type)
+ {
+ super(scheme, hostName, port, DEFAULT_PORT, userName, password, path, type);
+ this.share = share;
+ this.domain = domain;
+ }
+
+ /**
+ * Returns the share name.
+ * @return share name
+ */
+ public String getShare()
+ {
+ return share;
+ }
+
+ /**
+ * Builds the root URI for this file name.
+ */
+ @Override
+ protected void appendRootUri(final StringBuilder buffer, final boolean addPassword)
+ {
+ super.appendRootUri(buffer, addPassword);
+ buffer.append('/');
+ buffer.append(share);
+ }
+
+ /**
+ * Put {@code domain} before @{code username} if both are set.
+ * <p>
+ * Uses super method to add password or password placeholder.
+ */
+ @Override
+ protected void appendCredentials(final StringBuilder buffer, final boolean addPassword)
+ {
+ if (getDomain() != null && getDomain().length() != 0 &&
+ getUserName() != null && getUserName().length() != 0)
+ {
+ buffer.append(getDomain());
+ buffer.append("\\");
+ }
+ super.appendCredentials(buffer, addPassword);
+ }
+
+ /**
+ * Factory method for creating name instances.
+ *
+ * @param path path of file.
+ * @param type file or directory
+ * @return new SmbFileName object, never null.
+ */
+ @Override
+ public FileName createName(final String path, final FileType type)
+ {
+ return new SmbFileName(
+ getScheme(),
+ getHostName(),
+ getPort(),
+ getUserName(),
+ getPassword(),
+ domain,
+ share,
+ path,
+ type);
+ }
+
+ /**
+ * Construct the path suitable for SmbFile when used with NtlmPasswordAuthentication.
+ *
+ * @return caches and return URI with no username/password, never null
+ * @throws FileSystemException if any of the invoked methods throw
+ */
+ public String getUriWithoutAuth() throws FileSystemException
+ {
+ if (uriWithoutAuth != null)
+ {
+ return uriWithoutAuth;
+ }
+
+ final StringBuilder sb = new StringBuilder(120);
+ sb.append(getScheme());
+ sb.append("://");
+ sb.append(getHostName());
+ if (getPort() != DEFAULT_PORT)
+ {
+ sb.append(":");
+ sb.append(getPort());
+ }
+ sb.append("/");
+ sb.append(getShare());
+ sb.append(getPathDecoded());
+ uriWithoutAuth = sb.toString();
+ return uriWithoutAuth;
+ }
+
+ /**
+ * Returns the domain name.
+ * @return domain name
+ */
+ public String getDomain()
+ {
+ return domain;
+ }
+}
diff --git a/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/smb/SmbFileNameParser.java b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/smb/SmbFileNameParser.java
new file mode 100644
index 0000000..7d8cd3a
--- /dev/null
+++ b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/smb/SmbFileNameParser.java
@@ -0,0 +1,107 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.smb;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.provider.FileNameParser;
+import org.apache.commons.vfs2.provider.URLFileNameParser;
+import org.apache.commons.vfs2.provider.UriParser;
+import org.apache.commons.vfs2.provider.VfsComponentContext;
+
+/**
+ * Implementation for sftp. set default port to 139
+ */
+public class SmbFileNameParser extends URLFileNameParser
+{
+ private static final SmbFileNameParser INSTANCE = new SmbFileNameParser();
+ private static final int SMB_PORT = 139;
+
+ public SmbFileNameParser()
+ {
+ super(SMB_PORT);
+ }
+
+ public static FileNameParser getInstance()
+ {
+ return INSTANCE;
+ }
+
+ @Override
+ public FileName parseUri(final VfsComponentContext context, final FileName base,
+ final String filename) throws FileSystemException
+ {
+ final StringBuilder name = new StringBuilder();
+
+ // Extract the scheme and authority parts
+ final Authority auth = extractToPath(filename, name);
+
+ // extract domain
+ String username = auth.getUserName();
+ final String domain = extractDomain(username);
+ if (domain != null)
+ {
+ username = username.substring(domain.length() + 1);
+ }
+
+ // Decode and adjust separators
+ UriParser.canonicalizePath(name, 0, name.length(), this);
+ UriParser.fixSeparators(name);
+
+ // Extract the share
+ final String share = UriParser.extractFirstElement(name);
+ if (share == null || share.length() == 0)
+ {
+ throw new FileSystemException("vfs.provider.smb/missing-share-name.error", filename);
+ }
+
+ // Normalise the path. Do this after extracting the share name,
+ // to deal with things like smb://hostname/share/..
+ final FileType fileType = UriParser.normalisePath(name);
+ final String path = name.toString();
+
+ return new SmbFileName(
+ auth.getScheme(),
+ auth.getHostName(),
+ auth.getPort(),
+ username,
+ auth.getPassword(),
+ domain,
+ share,
+ path,
+ fileType);
+ }
+
+ private String extractDomain(final String username)
+ {
+ if (username == null)
+ {
+ return null;
+ }
+
+ for (int i = 0; i < username.length(); i++)
+ {
+ if (username.charAt(i) == '\\')
+ {
+ return username.substring(0, i);
+ }
+ }
+
+ return null;
+ }
+}
diff --git a/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/smb/SmbFileObject.java b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/smb/SmbFileObject.java
new file mode 100644
index 0000000..b6d863f
--- /dev/null
+++ b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/smb/SmbFileObject.java
@@ -0,0 +1,267 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.smb;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.MalformedURLException;
+
+import jcifs.smb.NtlmPasswordAuthentication;
+import jcifs.smb.SmbException;
+import jcifs.smb.SmbFile;
+import jcifs.smb.SmbFileInputStream;
+import jcifs.smb.SmbFileOutputStream;
+
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileType;
+import org.apache.commons.vfs2.FileTypeHasNoContentException;
+import org.apache.commons.vfs2.RandomAccessContent;
+import org.apache.commons.vfs2.UserAuthenticationData;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileObject;
+import org.apache.commons.vfs2.provider.UriParser;
+import org.apache.commons.vfs2.util.RandomAccessMode;
+import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
+
+/**
+ * A file in an SMB file system.
+ */
+public class SmbFileObject
+ extends AbstractFileObject<SmbFileSystem>
+{
+ // private final String fileName;
+ private SmbFile file;
+
+ protected SmbFileObject(final AbstractFileName name,
+ final SmbFileSystem fileSystem) throws FileSystemException
+ {
+ super(name, fileSystem);
+ // this.fileName = UriParser.decode(name.getURI());
+ }
+
+ /**
+ * Attaches this file object to its file resource.
+ */
+ @Override
+ protected void doAttach() throws Exception
+ {
+ // Defer creation of the SmbFile to here
+ if (file == null)
+ {
+ file = createSmbFile(getName());
+ }
+ }
+
+ @Override
+ protected void doDetach() throws Exception
+ {
+ // file closed through content-streams
+ file = null;
+ }
+
+ private SmbFile createSmbFile(final FileName fileName)
+ throws MalformedURLException, SmbException, FileSystemException
+ {
+ final SmbFileName smbFileName = (SmbFileName) fileName;
+
+ final String path = smbFileName.getUriWithoutAuth();
+
+ UserAuthenticationData authData = null;
+ SmbFile file;
+ try
+ {
+ authData = UserAuthenticatorUtils.authenticate(
+ getFileSystem().getFileSystemOptions(),
+ SmbFileProvider.AUTHENTICATOR_TYPES);
+
+ NtlmPasswordAuthentication auth = null;
+ if (authData != null)
+ {
+ auth = new NtlmPasswordAuthentication(
+ UserAuthenticatorUtils.toString(
+ UserAuthenticatorUtils.getData(authData, UserAuthenticationData.DOMAIN,
+ UserAuthenticatorUtils.toChar(smbFileName.getDomain()))),
+ UserAuthenticatorUtils.toString(
+ UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME,
+ UserAuthenticatorUtils.toChar(smbFileName.getUserName()))),
+ UserAuthenticatorUtils.toString(
+ UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD,
+ UserAuthenticatorUtils.toChar(smbFileName.getPassword()))));
+ }
+
+ // if auth == null SmbFile uses default credentials
+ // ("jcifs.smb.client.domain", "?"), ("jcifs.smb.client.username", "GUEST"),
+ // ("jcifs.smb.client.password", BLANK);
+ // ANONYMOUS=("","","")
+ file = new SmbFile(path, auth);
+
+ if (file.isDirectory() && !file.toString().endsWith("/"))
+ {
+ file = new SmbFile(path + "/", auth);
+ }
+ return file;
+ }
+ finally
+ {
+ UserAuthenticatorUtils.cleanup(authData); // might be null
+ }
+ }
+
+ /**
+ * Determines the type of the file, returns null if the file does not
+ * exist.
+ */
+ @Override
+ protected FileType doGetType() throws Exception
+ {
+ if (!file.exists())
+ {
+ return FileType.IMAGINARY;
+ }
+ else if (file.isDirectory())
+ {
+ return FileType.FOLDER;
+ }
+ else if (file.isFile())
+ {
+ return FileType.FILE;
+ }
+
+ throw new FileSystemException("vfs.provider.smb/get-type.error", getName());
+ }
+
+ /**
+ * Lists the children of the file. Is only called if {@link #doGetType}
+ * returns {@link FileType#FOLDER}.
+ */
+ @Override
+ protected String[] doListChildren() throws Exception
+ {
+ // VFS-210: do not try to get listing for anything else than directories
+ if (!file.isDirectory())
+ {
+ return null;
+ }
+
+ return UriParser.encode(file.list());
+ }
+
+ /**
+ * Determines if this file is hidden.
+ */
+ @Override
+ protected boolean doIsHidden() throws Exception
+ {
+ return file.isHidden();
+ }
+
+ /**
+ * Deletes the file.
+ */
+ @Override
+ protected void doDelete() throws Exception
+ {
+ file.delete();
+ }
+
+ @Override
+ protected void doRename(final FileObject newfile) throws Exception
+ {
+ file.renameTo(createSmbFile(newfile.getName()));
+ }
+
+ /**
+ * Creates this file as a folder.
+ */
+ @Override
+ protected void doCreateFolder() throws Exception
+ {
+ file.mkdir();
+ file = createSmbFile(getName());
+ }
+
+ /**
+ * Returns the size of the file content (in bytes).
+ */
+ @Override
+ protected long doGetContentSize() throws Exception
+ {
+ return file.length();
+ }
+
+ /**
+ * Returns the last modified time of this file.
+ */
+ @Override
+ protected long doGetLastModifiedTime()
+ throws Exception
+ {
+ return file.getLastModified();
+ }
+
+ /**
+ * Creates an input stream to read the file content from.
+ */
+ @Override
+ protected InputStream doGetInputStream() throws Exception
+ {
+ try
+ {
+ return new SmbFileInputStream(file);
+ }
+ catch (final SmbException e)
+ {
+ if (e.getErrorCode() == SmbException.ERRbadfile)
+ {
+ throw new org.apache.commons.vfs2.FileNotFoundException(getName());
+ }
+ else if (file.isDirectory())
+ {
+ throw new FileTypeHasNoContentException(getName());
+ }
+
+ throw e;
+ }
+ }
+
+ /**
+ * Creates an output stream to write the file content to.
+ */
+ @Override
+ protected OutputStream doGetOutputStream(final boolean bAppend) throws Exception
+ {
+ return new SmbFileOutputStream(file, bAppend);
+ }
+
+ /**
+ * random access
+ */
+ @Override
+ protected RandomAccessContent doGetRandomAccessContent(final RandomAccessMode mode) throws Exception
+ {
+ return new SmbFileRandomAccessContent(file, mode);
+ }
+
+ @Override
+ protected boolean doSetLastModifiedTime(final long modtime) throws Exception
+ {
+ file.setLastModified(modtime);
+ return true;
+ }
+}
diff --git a/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/smb/SmbFileProvider.java b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/smb/SmbFileProvider.java
new file mode 100644
index 0000000..9413954
--- /dev/null
+++ b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/smb/SmbFileProvider.java
@@ -0,0 +1,84 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.smb;
+
+import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileSystem;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.UserAuthenticationData;
+import org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider;
+import org.apache.commons.vfs2.provider.FileProvider;
+
+/**
+ * A provider for SMB (Samba, Windows share) file systems.
+ */
+public class SmbFileProvider
+ extends AbstractOriginatingFileProvider
+ implements FileProvider
+{
+ /** Authentication data supported by this provider. */
+ public static final UserAuthenticationData.Type[] AUTHENTICATOR_TYPES = new UserAuthenticationData.Type[]
+ {
+ UserAuthenticationData.USERNAME, UserAuthenticationData.PASSWORD, UserAuthenticationData.DOMAIN
+ };
+
+ static final Collection<Capability> capabilities =
+ Collections.unmodifiableCollection(Arrays.asList(new Capability[]
+ {
+ Capability.CREATE,
+ Capability.DELETE,
+ Capability.RENAME,
+ Capability.GET_TYPE,
+ Capability.GET_LAST_MODIFIED,
+ Capability.SET_LAST_MODIFIED_FILE,
+ Capability.SET_LAST_MODIFIED_FOLDER,
+ Capability.LIST_CHILDREN,
+ Capability.READ_CONTENT,
+ Capability.URI,
+ Capability.WRITE_CONTENT,
+ Capability.APPEND_CONTENT,
+ Capability.RANDOM_ACCESS_READ,
+ Capability.RANDOM_ACCESS_WRITE
+ }));
+
+ public SmbFileProvider()
+ {
+ super();
+ setFileNameParser(SmbFileNameParser.getInstance());
+ }
+
+ /**
+ * Creates the filesystem.
+ */
+ @Override
+ protected FileSystem doCreateFileSystem(final FileName name, final FileSystemOptions fileSystemOptions)
+ throws FileSystemException
+ {
+ return new SmbFileSystem(name, fileSystemOptions);
+ }
+
+ public Collection<Capability> getCapabilities()
+ {
+ return capabilities;
+ }
+}
diff --git a/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/smb/SmbFileRandomAccessContent.java b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/smb/SmbFileRandomAccessContent.java
new file mode 100644
index 0000000..73b9cd5
--- /dev/null
+++ b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/smb/SmbFileRandomAccessContent.java
@@ -0,0 +1,291 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.smb;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.net.MalformedURLException;
+import java.net.UnknownHostException;
+
+import jcifs.smb.SmbException;
+import jcifs.smb.SmbFile;
+import jcifs.smb.SmbRandomAccessFile;
+
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.provider.AbstractRandomAccessContent;
+import org.apache.commons.vfs2.util.RandomAccessMode;
+
+/**
+ * RandomAccess for smb files
+ */
+class SmbFileRandomAccessContent extends AbstractRandomAccessContent
+{
+ private final SmbRandomAccessFile raf;
+ private final InputStream rafis;
+
+ SmbFileRandomAccessContent(final SmbFile smbFile, final RandomAccessMode mode) throws FileSystemException
+ {
+ super(mode);
+
+ try
+ {
+ raf = new SmbRandomAccessFile(smbFile, mode.getModeString());
+ rafis = new InputStream()
+ {
+ @Override
+ public int available() throws IOException
+ {
+ final long available = raf.length() - raf.getFilePointer();
+ if (available > Integer.MAX_VALUE)
+ {
+ return Integer.MAX_VALUE;
+ }
+
+ return (int) available;
+ }
+
+ @Override
+ public void close() throws IOException
+ {
+ raf.close();
+ }
+
+ @Override
+ public int read() throws IOException
+ {
+ return raf.readByte();
+ }
+
+ @Override
+ public int read(final byte[] b) throws IOException
+ {
+ return raf.read(b);
+ }
+
+ @Override
+ public int read(final byte[] b, final int off, final int len) throws IOException
+ {
+ return raf.read(b, off, len);
+ }
+
+ @Override
+ public long skip(final long n) throws IOException
+ {
+ raf.seek(raf.getFilePointer() + n);
+ return n;
+ }
+ };
+ }
+ catch (final MalformedURLException e)
+ {
+ throw new FileSystemException("vfs.provider/random-access-open-failed.error", smbFile, e);
+ }
+ catch (final SmbException e)
+ {
+ throw new FileSystemException("vfs.provider/random-access-open-failed.error", smbFile, e);
+ }
+ catch (final UnknownHostException e)
+ {
+ throw new FileSystemException("vfs.provider/random-access-open-failed.error", smbFile, e);
+ }
+ }
+
+ public void close() throws IOException
+ {
+ raf.close();
+ }
+
+ public long getFilePointer() throws IOException
+ {
+ return raf.getFilePointer();
+ }
+
+ public InputStream getInputStream() throws IOException
+ {
+ return rafis;
+ }
+
+ public long length() throws IOException
+ {
+ return raf.length();
+ }
+
+ public boolean readBoolean() throws IOException
+ {
+ return raf.readBoolean();
+ }
+
+ public byte readByte() throws IOException
+ {
+ return raf.readByte();
+ }
+
+ public char readChar() throws IOException
+ {
+ return raf.readChar();
+ }
+
+ public double readDouble() throws IOException
+ {
+ return raf.readDouble();
+ }
+
+ public float readFloat() throws IOException
+ {
+ return raf.readFloat();
+ }
+
+ public void readFully(final byte[] b) throws IOException
+ {
+ raf.readFully(b);
+ }
+
+ public void readFully(final byte[] b, final int off, final int len) throws IOException
+ {
+ raf.readFully(b, off, len);
+ }
+
+ public int readInt() throws IOException
+ {
+ return raf.readInt();
+ }
+
+ public long readLong() throws IOException
+ {
+ return raf.readLong();
+ }
+
+ public short readShort() throws IOException
+ {
+ return raf.readShort();
+ }
+
+ public int readUnsignedByte() throws IOException
+ {
+ return raf.readUnsignedByte();
+ }
+
+ public int readUnsignedShort() throws IOException
+ {
+ return raf.readUnsignedShort();
+ }
+
+ public String readUTF() throws IOException
+ {
+ return raf.readUTF();
+ }
+
+ public void seek(final long pos) throws IOException
+ {
+ raf.seek(pos);
+ }
+
+ public void setLength(final long newLength) throws IOException
+ {
+ raf.setLength(newLength);
+ }
+
+ public int skipBytes(final int n) throws IOException
+ {
+ return raf.skipBytes(n);
+ }
+
+ @Override
+ public void write(final byte[] b) throws IOException
+ {
+ raf.write(b);
+ }
+
+ @Override
+ public void write(final byte[] b, final int off, final int len) throws IOException
+ {
+ raf.write(b, off, len);
+ }
+
+ @Override
+ public void write(final int b) throws IOException
+ {
+ raf.write(b);
+ }
+
+ @Override
+ public void writeBoolean(final boolean v) throws IOException
+ {
+ raf.writeBoolean(v);
+ }
+
+ @Override
+ public void writeByte(final int v) throws IOException
+ {
+ raf.writeByte(v);
+ }
+
+ @Override
+ public void writeBytes(final String s) throws IOException
+ {
+ raf.writeBytes(s);
+ }
+
+ @Override
+ public void writeChar(final int v) throws IOException
+ {
+ raf.writeChar(v);
+ }
+
+ @Override
+ public void writeChars(final String s) throws IOException
+ {
+ raf.writeChars(s);
+ }
+
+ @Override
+ public void writeDouble(final double v) throws IOException
+ {
+ raf.writeDouble(v);
+ }
+
+ @Override
+ public void writeFloat(final float v) throws IOException
+ {
+ raf.writeFloat(v);
+ }
+
+ @Override
+ public void writeInt(final int v) throws IOException
+ {
+ raf.writeInt(v);
+ }
+
+ @Override
+ public void writeLong(final long v) throws IOException
+ {
+ raf.writeLong(v);
+ }
+
+ @Override
+ public void writeShort(final int v) throws IOException
+ {
+ raf.writeShort(v);
+ }
+
+ @Override
+ public void writeUTF(final String str) throws IOException
+ {
+ raf.writeUTF(str);
+ }
+
+}
diff --git a/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/smb/SmbFileSystem.java b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/smb/SmbFileSystem.java
new file mode 100644
index 0000000..ed1942e
--- /dev/null
+++ b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/smb/SmbFileSystem.java
@@ -0,0 +1,57 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.smb;
+
+import java.util.Collection;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileName;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.FileSystemOptions;
+import org.apache.commons.vfs2.provider.AbstractFileName;
+import org.apache.commons.vfs2.provider.AbstractFileSystem;
+
+/**
+ * An SMB file system.
+ */
+public class SmbFileSystem
+ extends AbstractFileSystem
+{
+ protected SmbFileSystem(final FileName rootName, final FileSystemOptions fileSystemOptions)
+ {
+ super(rootName, null, fileSystemOptions);
+ }
+
+ /**
+ * Creates a file object.
+ */
+ @Override
+ protected FileObject createFile(final AbstractFileName name) throws FileSystemException
+ {
+ return new SmbFileObject(name, this);
+ }
+
+ /**
+ * Returns the capabilities of this file system.
+ */
+ @Override
+ protected void addCapabilities(final Collection<Capability> caps)
+ {
+ caps.addAll(SmbFileProvider.capabilities);
+ }
+}
diff --git a/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/smb/package.html b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/smb/package.html
new file mode 100644
index 0000000..b98b9e4
--- /dev/null
+++ b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/provider/smb/package.html
@@ -0,0 +1,19 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ -->
+<body>
+<p>VFS (Sandbox) SMB/CIFS File Provider.</p>
+</body>
diff --git a/trunk/sandbox/src/main/java/org/apache/commons/vfs2/util/FileObjectDataSource.java b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/util/FileObjectDataSource.java
new file mode 100644
index 0000000..d325898
--- /dev/null
+++ b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/util/FileObjectDataSource.java
@@ -0,0 +1,66 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.util;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+
+import javax.activation.DataSource;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+
+/**
+ * (Sandbox) Provide access to a FileObject as JAF DataSource.
+ */
+public class FileObjectDataSource implements DataSource
+{
+ private final FileObject fo;
+
+ public FileObjectDataSource(final FileObject fo)
+ {
+ this.fo = fo;
+ }
+
+ public InputStream getInputStream() throws IOException
+ {
+ return fo.getContent().getInputStream();
+ }
+
+ public OutputStream getOutputStream() throws IOException
+ {
+ return fo.getContent().getOutputStream();
+ }
+
+ public String getContentType()
+ {
+ try
+ {
+ return fo.getContent().getContentInfo().getContentType();
+ }
+ catch (final FileSystemException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public String getName()
+ {
+ return fo.getName().getBaseName();
+ }
+}
diff --git a/trunk/sandbox/src/main/java/org/apache/commons/vfs2/util/RACRandomAccessFile.java b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/util/RACRandomAccessFile.java
new file mode 100644
index 0000000..1ec9cad
--- /dev/null
+++ b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/util/RACRandomAccessFile.java
@@ -0,0 +1,149 @@
+/*
+ * Copyright 2002-2005 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.util;
+
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.RandomAccessFile;
+import org.apache.commons.vfs2.RandomAccessContent;
+
+/**
+ * (Sandbox) Encapsulates a {@link RandomAccessContent} instance, allowing it to be used
+ * as a {@link RandomAccessFile} instance.
+ */
+public class RACRandomAccessFile extends RandomAccessFile implements RandomAccessContent
+{
+ private final byte[] singleByteBuf = new byte[1];
+
+ private RandomAccessContent rac;
+
+ public RACRandomAccessFile(final RandomAccessContent rac) throws IOException
+ {
+ this(createTempFile());
+ this.rac = rac;
+ }
+
+ private RACRandomAccessFile(final File tempFile) throws IOException
+ {
+ super(tempFile, "r");
+ deleteTempFile(tempFile);
+ }
+
+ private static File createTempFile() throws IOException
+ {
+ return File.createTempFile("fraf", "");
+ }
+
+ private void deleteTempFile(final File tempFile)
+ {
+ try
+ {
+ super.close();
+ }
+ catch (final IOException ex)
+ {
+ throw new RuntimeException(ex);
+ }
+ finally
+ {
+ /* ignored = */ tempFile.delete();
+ }
+ }
+
+ @Override
+ public long getFilePointer() throws IOException
+ {
+ return this.rac.getFilePointer();
+ }
+
+ @Override
+ public void seek(final long pos) throws IOException
+ {
+ this.rac.seek(pos);
+ }
+
+ @Override
+ public int skipBytes(final int n) throws IOException
+ {
+ return this.rac.skipBytes(n);
+ }
+
+ @Override
+ public long length() throws IOException
+ {
+ return this.rac.length();
+ }
+
+ @Override
+ public void setLength(final long newLength) throws IOException
+ {
+ throw new IOException("Underlying RandomAccessContent instance length cannot be modified.");
+ }
+
+ public InputStream getInputStream() throws IOException
+ {
+ return this.rac.getInputStream();
+ }
+
+ @Override
+ public void close() throws IOException
+ {
+ this.rac.close();
+ }
+
+ @Override
+ public final int read(final byte[] b) throws IOException
+ {
+ return read(b, 0, b.length);
+ }
+
+ @Override
+ public final int read() throws IOException
+ {
+ final byte[] buf = this.singleByteBuf;
+ final int count = read(buf, 0, 1);
+ return count < 0 ? -1 : buf[0] & 0xFF;
+ }
+
+ @Override
+ public int read(final byte[] b, final int off, final int len) throws IOException
+ {
+ this.rac.readFully(b, off, len);
+ return len;
+ }
+
+ @Override
+ public final void write(final int b) throws IOException
+ {
+ final byte[] buf = this.singleByteBuf;
+ buf[0] = (byte) b;
+ write(buf, 0, 1);
+ }
+
+ @Override
+ public final void write(final byte[] b) throws IOException
+ {
+ write(b, 0, b.length);
+ }
+
+ @Override
+ public void write(final byte[] b, final int off, final int len) throws IOException
+ {
+ this.rac.write(b, off, len);
+ }
+
+}
diff --git a/trunk/sandbox/src/main/java/org/apache/commons/vfs2/util/SharedRandomContentInputStream.java b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/util/SharedRandomContentInputStream.java
new file mode 100644
index 0000000..2fbd130
--- /dev/null
+++ b/trunk/sandbox/src/main/java/org/apache/commons/vfs2/util/SharedRandomContentInputStream.java
@@ -0,0 +1,232 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.util;
+
+import java.io.BufferedInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashSet;
+import java.util.Set;
+
+import javax.mail.internet.SharedInputStream;
+
+import org.apache.commons.vfs2.Capability;
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.RandomAccessContent;
+
+/**
+ * (Sandbox) A wrapper to an FileObject to get a {@link javax.mail.internet.SharedInputStream}.
+ */
+public class SharedRandomContentInputStream extends BufferedInputStream implements SharedInputStream
+{
+ private final Set<SharedRandomContentInputStream> createdStreams;
+ private final FileObject fo;
+ private final long fileStart;
+ private final long fileEnd;
+
+ private long pos;
+ private long resetCount;
+
+ private SharedRandomContentInputStream(final Set<SharedRandomContentInputStream> createdStreams,
+ final FileObject fo, final long fileStart, final long fileEnd,
+ final InputStream is)
+ throws FileSystemException
+ {
+ super(is);
+
+ if (!fo.getFileSystem().hasCapability(Capability.RANDOM_ACCESS_READ))
+ {
+ throw new FileSystemException("vfs.util/missing-capability.error", Capability.RANDOM_ACCESS_READ);
+ }
+
+ this.fo = fo;
+ this.fileStart = fileStart;
+ this.fileEnd = fileEnd;
+ this.createdStreams = createdStreams;
+
+ synchronized (createdStreams)
+ {
+ createdStreams.add(this);
+ }
+ }
+
+ public SharedRandomContentInputStream(final FileObject fo) throws FileSystemException
+ {
+ this(new HashSet<SharedRandomContentInputStream>(), fo, 0, -1, fo.getContent().getInputStream());
+ }
+
+
+ @Override
+ public synchronized int read() throws IOException
+ {
+ if (checkEnd())
+ {
+ return -1;
+ }
+ final int r = super.read();
+ pos++;
+ resetCount++;
+ return r;
+ }
+
+ @Override
+ public synchronized int read(final byte[] b, final int off, int len) throws IOException
+ {
+ if (checkEnd())
+ {
+ return -1;
+ }
+
+ if (fileEnd > -1 && calcFilePosition(len) > fileEnd)
+ {
+ // we can not read past our end
+ len = (int) (fileEnd - getFilePosition());
+ }
+
+ final int nread = super.read(b, off, len);
+ pos += nread;
+ resetCount += nread;
+ return nread;
+ }
+
+ @Override
+ public synchronized long skip(long n) throws IOException
+ {
+ if (checkEnd())
+ {
+ return -1;
+ }
+
+ if (fileEnd > -1 && calcFilePosition(n) > fileEnd)
+ {
+ // we can not skip past our end
+ n = fileEnd - getFilePosition();
+ }
+
+ final long nskip = super.skip(n);
+ pos += nskip;
+ resetCount += nskip;
+ return nskip;
+ }
+
+ /*
+ public synchronized int available() throws IOException
+ {
+ long realFileEnd = fileEnd;
+ if (realFileEnd < 0)
+ {
+ realFileEnd = fo.getContent().getSize();
+ }
+ if (realFileEnd < 0)
+ {
+ // we cant determine if there is really something available
+ return 8192;
+ }
+
+ long available = realFileEnd - (fileStart + pos);
+ if (available > Integer.MAX_VALUE)
+ {
+ return Integer.MAX_VALUE;
+ }
+
+ return (int) available;
+ }
+ */
+
+ private boolean checkEnd()
+ {
+ return fileEnd > -1 && (getFilePosition() >= fileEnd);
+ }
+
+ protected long getFilePosition()
+ {
+ return fileStart + pos;
+ }
+
+ protected long calcFilePosition(final long nadd)
+ {
+ return getFilePosition() + nadd;
+ }
+
+ @Override
+ public synchronized void mark(final int readlimit)
+ {
+ super.mark(readlimit);
+ resetCount = 0;
+ }
+
+ @Override
+ public synchronized void reset() throws IOException
+ {
+ super.reset();
+ pos -= resetCount;
+ resetCount = 0;
+ }
+
+ public long getPosition()
+ {
+ return pos;
+ }
+
+
+ @Override
+ public void close() throws IOException
+ {
+ super.close();
+
+ synchronized (createdStreams)
+ {
+ createdStreams.remove(this);
+ }
+ }
+
+ public InputStream newStream(final long start, final long end)
+ {
+ try
+ {
+ final long newFileStart = this.fileStart + start;
+ final long newFileEnd = end < 0 ? this.fileEnd : this.fileStart + end;
+
+ final RandomAccessContent rac = fo.getContent().getRandomAccessContent(RandomAccessMode.READ);
+ rac.seek(newFileStart);
+ return new SharedRandomContentInputStream(
+ createdStreams,
+ fo,
+ newFileStart,
+ newFileEnd,
+ rac.getInputStream());
+ }
+ catch (final IOException e)
+ {
+ throw new RuntimeException(e);
+ }
+ }
+
+ public void closeAll() throws IOException
+ {
+ synchronized (createdStreams)
+ {
+ final SharedRandomContentInputStream[] streams = new SharedRandomContentInputStream[createdStreams.size()];
+ createdStreams.toArray(streams);
+ for (final SharedRandomContentInputStream stream : streams)
+ {
+ stream.close();
+ }
+ }
+ }
+}
diff --git a/trunk/sandbox/src/main/resources/META-INF/vfs-providers.xml b/trunk/sandbox/src/main/resources/META-INF/vfs-providers.xml
new file mode 100644
index 0000000..45fb237
--- /dev/null
+++ b/trunk/sandbox/src/main/resources/META-INF/vfs-providers.xml
@@ -0,0 +1,33 @@
+<?xml version="1.0"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+ -->
+<providers>
+
+ <provider class-name="org.apache.commons.vfs2.provider.smb.SmbFileProvider">
+ <scheme name="smb"/>
+ <if-available class-name="jcifs.smb.SmbFile"/>
+ </provider>
+
+ <provider class-name="org.apache.commons.vfs2.provider.mime.MimeFileProvider">
+ <scheme name="mime"/>
+ <if-available class-name="javax.mail.internet.MimeMultipart"/>
+ </provider>
+
+ <extension-map extension="mime" scheme="mime"/>
+ <mime-type-map mime-type="message/rfc822" scheme="mime"/>
+
+</providers>
diff --git a/trunk/sandbox/src/site/site.xml b/trunk/sandbox/src/site/site.xml
new file mode 100644
index 0000000..6c554a8
--- /dev/null
+++ b/trunk/sandbox/src/site/site.xml
@@ -0,0 +1,35 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<project name="Commons VFS">
+
+ <bannerRight>
+ <name>Commons VFS</name>
+ <src>../images/vfs-logo-white.png</src>
+ <href>../index.html</href>
+ </bannerRight>
+
+ <body>
+ <links>
+ <item name="Commons VFS Home" href="../index.html"/>
+ </links>
+
+ <!-- menu inherited -->
+
+ <menu ref="reports"/>
+ </body>
+</project>
diff --git a/trunk/sandbox/src/site/xdoc/index.xml b/trunk/sandbox/src/site/xdoc/index.xml
new file mode 100644
index 0000000..62bd0fe
--- /dev/null
+++ b/trunk/sandbox/src/site/xdoc/index.xml
@@ -0,0 +1,47 @@
+<?xml version="1.0"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<document>
+ <properties>
+ <title>Apache Commons VFS Sandbox</title>
+ <author email="dev@commons.apache.org">Apache Commons Developers</author>
+ </properties>
+
+ <body>
+
+ <section name="About Apache Commons VFS Sandbox">
+ <p>
+ This sandbox module contains VFS packages (<a href="../filesystems.html">filesystem
+ providers</a>) which cannot be shipped with the official Apache release.
+ This includes experimental code as well as components which have
+ <a href="dependencies.html">dependencies</a> not compatible with the
+ <a href="http://www.apache.org/legal/resolved.html#category-x">ASF redistribution policy
+ (especially LGPL)</a>.
+ </p><p>
+ To build the sandbox binaries, see the <a href="../download.html">download and build
+ instructions</a>.
+ Make sure to enable the sandbox maven profile with <code>-Pinclude-sandbox</code>.
+ If you use <code>mvn install</code> the sandbox binary archive can be used from
+ the local repository. If you are not using the released source archive, you may have
+ to adjust the parent-version and version-numbers if you want to avoid SNAPSHOT
+ artifacts.
+ </p>
+ </section>
+
+ </body>
+</document>
diff --git a/trunk/sandbox/src/test/java/org/apache/commons/vfs2/provider/smb/test/FileNameTestCase.java b/trunk/sandbox/src/test/java/org/apache/commons/vfs2/provider/smb/test/FileNameTestCase.java
new file mode 100644
index 0000000..585836e
--- /dev/null
+++ b/trunk/sandbox/src/test/java/org/apache/commons/vfs2/provider/smb/test/FileNameTestCase.java
@@ -0,0 +1,160 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.smb.test;
+
+import org.apache.commons.AbstractVfsTestCase;
+import org.apache.commons.vfs2.FileSystemException;
+import org.apache.commons.vfs2.provider.smb.SmbFileName;
+import org.apache.commons.vfs2.provider.smb.SmbFileNameParser;
+
+/**
+ * Some additional SMB file name test cases.
+ */
+public class FileNameTestCase
+ extends AbstractVfsTestCase
+{
+ /**
+ * Tests parsing a URI into its parts.
+ * @throws Exception in case of error
+ */
+ public void testParseUri() throws Exception
+ {
+ // Simple name
+ SmbFileName name = (SmbFileName) SmbFileNameParser.getInstance().parseUri(null, null, "smb://hostname/share/file");
+ assertEquals("smb", name.getScheme());
+ assertNull(name.getUserName());
+ assertNull(name.getPassword());
+ assertEquals("hostname", name.getHostName());
+ assertEquals(139, name.getPort());
+ assertEquals(name.getDefaultPort(), name.getPort());
+ assertEquals("share", name.getShare());
+ assertEquals("/file", name.getPath());
+ assertEquals("smb://hostname/share/", name.getRootURI());
+ assertEquals("smb://hostname/share/file", name.getURI());
+
+ // Name with port
+ name = (SmbFileName) SmbFileNameParser.getInstance().parseUri(null, null, "smb://hostname:9090/share/file");
+ assertEquals("smb", name.getScheme());
+ assertNull(name.getUserName());
+ assertNull(name.getPassword());
+ assertEquals("hostname", name.getHostName());
+ assertEquals(9090, name.getPort());
+ assertEquals("share", name.getShare());
+ assertEquals("/file", name.getPath());
+ assertEquals("smb://hostname:9090/share/", name.getRootURI());
+ assertEquals("smb://hostname:9090/share/file", name.getURI());
+
+ // Name with no path
+ name = (SmbFileName) SmbFileNameParser.getInstance().parseUri(null, null, "smb://hostname/share");
+ assertEquals("smb", name.getScheme());
+ assertNull(name.getUserName());
+ assertNull(name.getPassword());
+ assertEquals("hostname", name.getHostName());
+ assertEquals(139, name.getPort());
+ assertEquals("share", name.getShare());
+ assertEquals("/", name.getPath());
+ assertEquals("smb://hostname/share/", name.getRootURI());
+ assertEquals("smb://hostname/share/", name.getURI());
+
+ // Name with username
+ name = (SmbFileName) SmbFileNameParser.getInstance().parseUri(null, null, "smb://user@hostname/share/file");
+ assertEquals("smb", name.getScheme());
+ assertEquals("user", name.getUserName());
+ assertNull(name.getPassword());
+ assertEquals("hostname", name.getHostName());
+ assertEquals(139, name.getPort());
+ assertEquals("share", name.getShare());
+ assertEquals("/file", name.getPath());
+ assertEquals("smb://user@hostname/share/", name.getRootURI());
+ assertEquals("smb://user@hostname/share/file", name.getURI());
+
+ // Name with extension
+ name = (SmbFileName) SmbFileNameParser.getInstance().parseUri(null, null, "smb://user@hostname/share/file.txt");
+ assertEquals("smb", name.getScheme());
+ assertEquals("user", name.getUserName());
+ assertNull(name.getPassword());
+ assertEquals("hostname", name.getHostName());
+ assertEquals(139, name.getPort());
+ assertEquals("share", name.getShare());
+ assertEquals("/file.txt", name.getPath());
+ assertEquals("file.txt", name.getBaseName());
+ assertEquals("txt", name.getExtension());
+ assertEquals("smb://user@hostname/share/", name.getRootURI());
+ assertEquals("smb://user@hostname/share/file.txt", name.getURI());
+
+ // Name look likes extension, but isnt
+ name = (SmbFileName) SmbFileNameParser.getInstance().parseUri(null, null, "smb://user@hostname/share/.bashrc");
+ assertEquals("smb", name.getScheme());
+ assertEquals("user", name.getUserName());
+ assertNull(name.getPassword());
+ assertEquals("hostname", name.getHostName());
+ assertEquals(139, name.getPort());
+ assertEquals("share", name.getShare());
+ assertEquals("/.bashrc", name.getPath());
+ assertEquals(".bashrc", name.getBaseName());
+ assertEquals("", name.getExtension());
+ assertEquals("smb://user@hostname/share/", name.getRootURI());
+ assertEquals("smb://user@hostname/share/.bashrc", name.getURI());
+ }
+
+ /**
+ * Tests error handling in URI parser.
+ * @throws Exception in case of error
+ */
+ public void testBadlyFormedUri() throws Exception
+ {
+ // Does not start with smb://
+ testBadlyFormedUri("smb:", "vfs.provider/missing-double-slashes.error");
+ testBadlyFormedUri("smb:/", "vfs.provider/missing-double-slashes.error");
+ testBadlyFormedUri("smb:a", "vfs.provider/missing-double-slashes.error");
+
+ // Missing hostname
+ testBadlyFormedUri("smb://", "vfs.provider/missing-hostname.error");
+ testBadlyFormedUri("smb://:21/share", "vfs.provider/missing-hostname.error");
+ testBadlyFormedUri("smb:///share", "vfs.provider/missing-hostname.error");
+
+ // Empty port
+ testBadlyFormedUri("smb://host:", "vfs.provider/missing-port.error");
+ testBadlyFormedUri("smb://host:/share", "vfs.provider/missing-port.error");
+ testBadlyFormedUri("smb://host:port/share/file", "vfs.provider/missing-port.error");
+
+ // Missing absolute path
+ testBadlyFormedUri("smb://host:90a", "vfs.provider/missing-hostname-path-sep.error");
+ testBadlyFormedUri("smb://host?a", "vfs.provider/missing-hostname-path-sep.error");
+
+ // Missing share name
+ testBadlyFormedUri("smb://host", "vfs.provider.smb/missing-share-name.error");
+ testBadlyFormedUri("smb://host/", "vfs.provider.smb/missing-share-name.error");
+ testBadlyFormedUri("smb://host:9090/", "vfs.provider.smb/missing-share-name.error");
+ }
+
+ /**
+ * Assert that parsing a URI fails with the expected error.
+ */
+ private void testBadlyFormedUri(final String uri, final String errorMsg)
+ {
+ try
+ {
+ SmbFileNameParser.getInstance().parseUri(null, null, uri);
+ fail();
+ }
+ catch (final FileSystemException e)
+ {
+ assertSameMessage(errorMsg, uri, e);
+ }
+ }
+}
diff --git a/trunk/sandbox/src/test/java/org/apache/commons/vfs2/provider/smb/test/SmbProviderTestCase.java b/trunk/sandbox/src/test/java/org/apache/commons/vfs2/provider/smb/test/SmbProviderTestCase.java
new file mode 100644
index 0000000..1ad9820
--- /dev/null
+++ b/trunk/sandbox/src/test/java/org/apache/commons/vfs2/provider/smb/test/SmbProviderTestCase.java
@@ -0,0 +1,68 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.apache.commons.vfs2.provider.smb.test;
+
+import junit.framework.Test;
+
+import org.apache.commons.vfs2.FileObject;
+import org.apache.commons.vfs2.FileSystemManager;
+import org.apache.commons.vfs2.impl.DefaultFileSystemManager;
+import org.apache.commons.vfs2.provider.smb.SmbFileProvider;
+import org.apache.commons.vfs2.test.AbstractProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestConfig;
+import org.apache.commons.vfs2.test.ProviderTestSuite;
+
+/**
+ * Tests for the SMB file system.
+ */
+public class SmbProviderTestCase
+ extends AbstractProviderTestConfig
+ implements ProviderTestConfig
+{
+ private static final String TEST_URI = "test.smb.uri";
+ public static Test suite() throws Exception
+ {
+ if (System.getProperty(TEST_URI) != null)
+ {
+ return new ProviderTestSuite(new SmbProviderTestCase());
+ }
+ else
+ {
+ return notConfigured(SmbProviderTestCase.class);
+ }
+ }
+
+ /**
+ * Prepares the file system manager.
+ */
+ @Override
+ public void prepare(final DefaultFileSystemManager manager)
+ throws Exception
+ {
+ manager.addProvider("smb", new SmbFileProvider());
+ }
+
+ /**
+ * Returns the base folder for tests.
+ */
+ @Override
+ public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception
+ {
+ final String uri = System.getProperty(TEST_URI);
+ return manager.resolveFile(uri);
+ }
+}
diff --git a/trunk/src/changes/changes.xml b/trunk/src/changes/changes.xml
new file mode 100644
index 0000000..0700dc1
--- /dev/null
+++ b/trunk/src/changes/changes.xml
@@ -0,0 +1,599 @@
+<?xml version="1.0"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<document xmlns="http://maven.apache.org/changes/1.0.0">
+ <properties>
+ <title>Apache Commons VFS Changes</title>
+ <author email="dev@commons.apache.org">Apache Commons Developers</author>
+ </properties>
+
+ <body>
+ <release version="2.1" date="TBD" description="New features and bug fix release.">
+<!-- <action issue="VFS-443" dev="ggregory" type="update" due-to="nickallen"> -->
+<!-- [Local] Need an easy way to convert from a FileObject to a File. -->
+<!-- </action> -->
+ <action issue="VFS-424" dev="ecki" type="fix">
+ Fix StandardFileSystemManager class loading so it works in a OSGi environment.
+ </action>
+ <action issue="VFS-490" dev="ecki" type="fix">
+ [vfsclassloader] Do not open folders with .jar extension. Adds tests.
+ </action>
+ <action issue="VFS-582" dev="ecki" type="fix">
+ [tests] revert rename of getTestDirectoryFile to make test classes more compatible for external providers.
+ </action>
+ <action issue="VFS-480" dev="ecki" type="fix">
+ Make startup of SoftRefsFileCache cleaner thread work and less racy to avoid leaks.
+ </action>
+ <action issue="VFS-549" dev="ecki" type="fix">
+ Use File.seperator instead of getProperty("file.separator").
+ </action>
+ <action issue="VFS-567" dev="ecki" type="fix" due-to="Antonio Petrelli">
+ [ftp] Ignore exceptions while QUIT/disconnect.
+ </action>
+ <action issue="VFS-572" dev="ecki" type="fix" due-to="Sandra Parsick">
+ [sftp] better documentation for knownhosts file option.
+ </action>
+ <action issue="VFS-574" dev="ecki" type="fix">
+ Ensure FileOpertionProviders are closed. Adds some testcases.
+ The error code for missing operations exceptions corrected: vfs.operation/operation-not-supported.error
+ </action>
+ <action issue="VFS-279" dev="ecki" type="fix" due-to="Didier Earith, Simon Legner">
+ [local] Avoid ClassCastException when replicating local files while OnCall caching is active.
+ </action>
+ <action issue="VFS-297" dev="joehni" type="fix" due-to="Kirill Safonov, Jimmy Praet">
+ [sftp] VSF fails to reuse FileSystem instances if FileSystemOptions contain
+ an array as value. Reported for SFTP using identities.
+ </action>
+ <action issue="VFS-198" dev="ecki" type="add" due-to="Andrew Franklin, Simon Legner">
+ [http] Make user agent configurable.
+ </action>
+ <action issue="VFS-202" dev="ecki" type="fix" due-to="Sergey Vladimirov, Simon Legner">
+ [http] Allow URLs responding with 405 to HEAD requests.
+ </action>
+ <action issue="VFS-490" dev="ecki" type="fix">
+ [hdfs] Make OSGi package imports for hdfs resolution=optional.
+ Removed all scopes from dependency management.
+ </action>
+ <action issue="VFS-560" dev="ecki" type="fix">
+ [http] avoid initial HEAD request to root of HttpFileSystem as it might be wrong context.
+ </action>
+ <action issue="VFS-236" dev="ecki" type="fix" due-to="Matt Casters">
+ [smb] Allow SMB to be used with no authentication.
+ </action>
+ <action issue="VFS-564" dev="ecki" type="fix" due-to="Dmitry Konstantinov">
+ Make some loggers static.
+ </action>
+ <action issue="VFS-555" dev="rwhitcomb" type="add">
+ [hdfs] Add the ability to specify an HDFS configuration file with HdfsFileSystemConfigBuilder.
+ </action>
+ <action issue="VFS-557" dev="ecki" type="fix">
+ [webdav][test] Create WebDav test directory in target/test. Avoid creating core/jackrabbit/tmp.
+ Logfiles of Jackrabbit are preserved when -DWebdavProviderTestCase.Debug=true is specified.
+ </action>
+ <action issue="VFS-558" dev="ecki" type="fix">
+ Make moveTo() and getParent() work with CacheStrategy.ON_CALL.
+ In case of FTP Provider it would lead otherwise to an UnsupportedOperationException.
+ </action>
+ <action dev="ecki" type="fix">
+ [sandbox] RACRandomAccessFile is now in org.apache.commons.vfs2.util package (so sandbox has only one overlapping package).
+ </action>
+ <action issue="VFS-530" dev="ecki" type="update" due-to="Dave Marion">
+ [hdfs] Use stable Apache Hadoop 2.6 dependencies.
+ </action>
+ <action dev="ecki" type="add">
+ [example] make VFS Shell print version and implement new 'info' command.
+ </action>
+ <action issue="VFS-552" dev="ecki" type="fix">
+ [sandbox] include vfs-providers.xml in JAR for dynamic registration of mime and smb providers.
+ </action>
+ <action issue="VFS-551" dev="ecki" type="fix" due-to="David Camilo Espitia Manrique">
+ Javadoc: make it clear that DefaultCryptor is only an obfuscation function.
+ </action>
+ <action issue="VFS-309" dev="ecki" type="fix">
+ DefaultFileContent will remove thread data whenever possible to avoid leaks.
+ </action>
+ <action issue="VFS-487" dev="ecki" type="fix" due-to="Dave Marion">
+ DefaultFileMonitor detects recreated files.
+ </action>
+ <action issue="VFS-523" dev="ecki" type="fix" due-to="Roger Whitcomb">
+ [HDFS] Make HdfsFileObject.equal use system hashcode/equals instead of
+ wrongly comparing file path only.
+ </action>
+ <action issue="VFS-544" dev="ecki" type="fix">
+ [Virtual] Allow virtual file systems and virtual file system provider
+ to be closed, to avoid memory leak.
+ </action>
+ <action issue="VFS-142" dev="ecki" type="fix" due-to="Ryan Boettcher">
+ Use ThreadLocal.remove() to clean out FileContentThreadData objects.
+ </action>
+ <action issue="VFS-545" dev="ecki" type="fix">
+ Make DefaultFilesCache remove reference to filesystem when it is cleared (closed).
+ </action>
+ <action issue="VFS-521" dev="ecki" type="fix">
+ [Ram][Tests] Make RAM provider test pass on Java 8
+ (JDK-8042377, self-suppression not permitted, MonitorOutputStream#close()).
+ </action>
+ <action issue="VFS-601" dev="ggregory" type="update">
+ Update Apache Commons Net from 3.3 to 3.4.
+ </action>
+ <action issue="VFS-602" dev="ggregory" type="update">
+ Update Apache Commons IO from 2.4 to 2.5.
+ </action>
+ <action issue="VFS-579" dev="ggregory" type="update">
+ Update Jsch from 0.1.51 to 0.1.53.
+ </action>
+ <action issue="VFS-542" dev="ggregory" type="update">
+ Update Jsch from 0.1.50 to 0.1.51.
+ </action>
+ <action issue="VFS-578" dev="ggregory" type="update">
+ Update Apache Commons Compress from 1.9 to 1.10.
+ </action>
+ <action issue="VFS-541" dev="ggregory" type="update">
+ Update Apache Commons Compress from 1.6 to 1.9.
+ </action>
+ <action issue="VFS-540" dev="ggregory" type="update">
+ Update Apache Commons Logging from 1.1.3 to 1.2.
+ </action>
+ <action issue="VFS-539" dev="ggregory" type="update">
+ Update Apache Commons Lang from 3.1 to 3.3.2.
+ </action>
+ <action issue="VFS-532" dev="ggregory" type="add" due-to="Gareth Daniel Smith">
+ [FTP] Allow configuring remoteVerificationEnabled on FTPClient instances.
+ </action>
+ <action issue="VFS-338" dev="ecki" type="fix" due-to="Daniel R.">
+ [Local][Tests] Avoid IndexOutOfBoundsException when validating local file URIs.
+ </action>
+ <action issue="VFS-526" dev="ecki" type="update">
+ [HDFS][Tests] Support HDFS testing on Windows (but keep profile "no-hdfs" enabled on Windows VFS-529).
+ </action>
+ <action issue="VFS-453" dev="ecki" type="update" due-to="Jiri Syrovy">
+ [HTTP][WEBDAV] Add file system options for connect and socket timeout.
+ </action>
+ <action issue="VFS-167" dev="ecki" type="update" due-to="Jimmy Praet">
+ [FTP] Allow Proxy support to file system options.
+ </action>
+ <action issue="VFS-520" dev="ecki" type="update">
+ Make JavaDoc compatible with Java 8 tool.
+ </action>
+ <action issue="VFS-518" dev="ggregory" type="update" due-to="Roland Illig">
+ Documentation of FileSystemOptions should be more helpful.
+ </action>
+ <action issue="VFS-500" dev="ggregory" type="update" due-to="Bernd Eckenfels">
+ VFSClassLoader.findResources missing.
+ </action>
+ <action issue="VFS-514" dev="ggregory" type="update" due-to="Bernd Eckenfels">
+ [tests] PermissionsTests leaves unclean test directory.
+ </action>
+ <action issue="VFS-501" dev="ggregory" type="update" due-to="Yves Schumann">
+ Hide passwords from log/console output.
+ </action>
+ <action issue="VFS-496" dev="ggregory" type="update" due-to="Bernd Eckenfels">
+ Resource translation issues.
+ </action>
+ <action issue="VFS-494" dev="ggregory" type="update" due-to="Allen Xudong Cheng">
+ [SFTP] No support for SFTP servers with non Latin-1 file name encoding.
+ </action>
+ <action issue="VFS-368" dev="ggregory" type="update" due-to="Brendan Long">
+ [SFTP] Documentation implies that "userDirIsRoot" defaults to true.
+ </action>
+ <action issue="VFS-265" dev="ggregory" type="update" due-to="Scott Bjerstedt">
+ [FTP] Set user dir as root dir by default.
+ </action>
+ <action issue="VFS-489" dev="ggregory" type="fix" due-to="Bernd Eckenfels">
+ [tests] ProviderWriteTests#testListener does not fail cleanly.
+ </action>
+ <action issue="VFS-486" dev="ggregory" type="fix" due-to="Sam Haldane">
+ DefaultFileMonitor sleeps for twice the specified delay when checkPerRun > 0.
+ </action>
+ <action issue="VFS-484" dev="ggregory" type="update">
+ [SFTP] Update Jsch to 0.1.50 from 0.1.49.
+ </action>
+ <action issue="VFS-482" dev="ggregory" type="fix">
+ Wrong assertion messages in RAM provider test case.
+ </action>
+ <action issue="VFS-507" dev="ggregory" type="update">
+ Update to Apache Commons Collection 4.1 from 3.2.1 and use generics.
+ </action>
+ <action issue="VFS-476" dev="ggregory" type="update">
+ Update Apache Commons Logging to 1.1.3 from 1.1.2.
+ </action>
+ <action issue="VFS-475" dev="ggregory" type="update">
+ Update Apache Commons Net to 3.3 from 3.2.
+ </action>
+ <action issue="VFS-506" dev="ggregory" type="update">
+ [Tar][Bzip2] Update Apache Commons Compress to 1.6 from 1.5.
+ </action>
+ <action issue="VFS-471" dev="ggregory" type="update">
+ Update to Apache Commons Compress 1.5.
+ </action>
+ <action issue="VFS-469" dev="joehni" type="remove">
+ Remove unused dependency to javax.jcr:jcr.
+ </action>
+ <action issue="VFS-283" dev="joehni" type="update">
+ [SFTP] SFTP provider did not support passphrase-protected keys nor the exchange of a public key with
+ a requesting SFTP server. To support such triples (private key/passphrase/public key) instead of private
+ keys only, a new structure EntityInfo has been created. SftpFileSystemConfigBuilder has now the new
+ getter and setter methods getIdentityInfo and setIdentity info which replace the now deprecated methods
+ getIdentities and setIdentities.
+ </action>
+ <action issue="VFS-460" dev="joehni" type="fix">
+ Dependency to commons-compress set as optional.
+ </action>
+ <action issue="VFS-468" dev="joehni" type="add">
+ [FTPS] Add option for KeyManager (and TrustManager) to support FTPS servers that ask for the client certificate for authentication.
+ </action>
+ <action issue="VFS-464" dev="joehni" type="fix">
+ StaticUserAuthenticator should return only requested authentication data.
+ </action>
+ <action issue="VFS-463" dev="joehni" type="update">
+ FileSytemConfigBuilder supports system properties for the value of enum-based configuration entries.
+ </action>
+ <action issue="VFS-462" dev="joehni" type="update">
+ [FTPS] Deprecate FtpsFileSystemConfigBuilder.setFtpsType and FtpsFileSystemConfigBuilder.getFtpsType
+ in favor of FtpsFileSystemConfigBuilder.setFtpsMode and FtpsFileSystemConfigBuilder.getFtpsMode which
+ use new enum FtpsMode instead.
+ </action>
+ <action issue="VFS-461" dev="joehni" type="fix">
+ [FTP/FTPS] ConfigBuilder does not consider system properties for the value of SoTimeout and Encoding.
+ </action>
+ <action issue="VFS-412" dev="joehni" type="add" due-to="Jose Juan Montiel">
+ [FTPS] Add support for command to set the DataChannelProtectionLevel.
+ </action>
+ <action issue="VFS-459" dev="joehni" type="update">
+ [FTP/FTPS] Sent commands and the received answer is logged at debug level.
+ </action>
+ <action issue="VFS-458" dev="joehni" type="fix">
+ [FTPS] Provider missed functionality and bug fixes already available for the FTP provider.
+ </action>
+ <action issue="VFS-452" dev="ggregory" type="fix" due-to="Jean-Marc Borer">
+ [HTTP] HttpFileObject read/write attributes should reflect underlying FileSystem capabilities.
+ </action>
+ <action issue="VFS-285" dev="tn" type="fix" due-to="Kirill Safonov">
+ AbstractFileObject.getChildren() may corrupt its internal state if a filename
+ can not be resolved.
+ </action>
+ <action issue="VFS-450" dev="ggregory" type="fix" due-to="Dave Marion">
+ [HDFS] HDFSFileSystem.resolveFile() does not honor CacheStrategy.ON_RESOLVE.
+ </action>
+ <action issue="VFS-442" dev="ggregory" type="add" due-to="Dave Marion">
+ [HDFS] Add an HDFS FileSystem Provider.
+ </action>
+ <action issue="VFS-448" dev="ggregory" type="fix">
+ commons-vfs 2.0 JAR has flawed OSGi MANIFEST.MF.
+ </action>
+ <action issue="VFS-447" dev="ggregory" type="add">
+ [FTP/FTPS] Update Apache Commons Net to 3.2 from 3.1.
+ </action>
+ <action issue="VFS-445" dev="ggregory" type="add">
+ Add FileSystemManager.resolveFile(URI) and resolveFile(URL).
+ </action>
+ <action issue="VFS-440" dev="ggregory" type="add" due-to="bpiwowar">
+ [SFTP] Stream (e.g. netcat) proxy for Sftp file system (aka ProxyCommand).
+ </action>
+ <action issue="VFS-439" dev="ggregory" type="fix" due-to="pensecit">
+ StaticUserAuthenticator usage example wrong.
+ </action>
+ <action issue="VFS-437" dev="ggregory" type="fix" due-to="denniszhu, danttran, jpowang">
+ [FTP] StackOverFlowError getting the type of a directory with a symbolic link to a parent directory with the same name.
+ </action>
+ <action issue="VFS-435" dev="ggregory" type="fix" due-to="george scott">
+ FileSystemConfigBuilder does not use prefix for some system property lookups.
+ </action>
+ <action issue="VFS-434" dev="ggregory" type="fix">
+ FileSystemException should reuse IOException's chained exception.
+ </action>
+ <action issue="VFS-433" dev="ggregory" type="fix">
+ [WebDAV] Message "vfs.provider.webdav/propfind.error" is not defined.
+ </action>
+ <action issue="VFS-430" dev="ggregory" type="fix" due-to="antonin.stefanutti">
+ The SoftRefFilesCache class logs clear text password.
+ </action>
+ <action issue="VFS-432" dev="ggregory" type="add">
+ [HTTP][WebDAV] Allow HTTP follow redirect.
+ </action>
+ <action issue="VFS-431" dev="ggregory" type="add">
+ FileSystemOption does not implement toString().
+ </action>
+ <action issue="VFS-429" dev="ggregory" type="fix">
+ Remove extra FileSystem ivar in AbstractFileObject subclasses with generics.
+ </action>
+ <action issue="VFS-427" dev="ggregory" type="fix" due-to="awelynant">
+ [HTTP] NPE on HttpFileObject.getContent().getContentInfo().
+ </action>
+ <action issue="VFS-405" dev="ggregory" type="add" due-to="dwaszak">
+ Get/set the file permissions.
+ </action>
+ <action issue="VFS-457" dev="joehni" type="update">
+ Update test dependencies: sshd-core version 0.7.0 to 0.8.0; mina-core 2.0.4 to 2.0.7; junit 4.11 to 4.12; slf4j-* 1.5.5 to 1.5.11
+ </action>
+ <action issue="VFS-456" dev="joehni" type="update">
+ Use org.bouncycastel:bcprov-jdk16 instead of org.bouncycastle:bcprof-jdk15on since Java 1.6 is required.
+ </action>
+ <action issue="VFS-415" dev="ggregory" type="update">
+ Update VFS requirement to Java 1.6.
+ </action>
+ <action issue="VFS-426" dev="ggregory" type="add" due-to="daniel.bergholm">
+ HTTP URL query string not part of cache key.
+ </action>
+ <action issue="VFS-425" dev="ggregory" type="add">
+ Add API FileObject.isExecutable().
+ </action>
+ <action issue="VFS-421" dev="ggregory" type="add" due-to="bpiwowar">
+ [SFTP] Configure a custom Identity Repository.
+ </action>
+ <action issue="VFS-418" dev="ggregory" type="update">
+ Update to Apache Commons Compress 1.4.1.
+ </action>
+ <action issue="VFS-417" dev="ggregory" type="add">
+ [RAM][Local] Add and implement new API: RandomAccessContent.setLength(long).
+ </action>
+ <action issue="VFS-406" dev="ggregory" type="fix" due-to="mp1">
+ [RAM] resize throws ArrayOOBE when shrinking in size.
+ </action>
+ <action issue="VFS-321" dev="ggregory" type="update" due-to="sebb">
+ AbstractFileObject sometimes uses getFileSystem() and sometimes references "fs" field directly.
+ </action>
+ <action issue="VFS-327" dev="ggregory" type="update" due-to="sebb">
+ UriParser.canonicalizePath possible NPE for filenameParser.
+ </action>
+ <action issue="VFS-353" dev="ggregory" type="fix" due-to="bergander">
+ [FTP] Client should call logout before disconnecting.
+ </action>
+ <action issue="VFS-408" dev="ggregory" type="fix" due-to="anilm2@yahoo.com">
+ CompressedFileFileObject Exception thrown when container file has no extension.
+ </action>
+ <action issue="VFS-400" dev="ggregory" type="add">
+ Add a FileSelector based on regular expressions.
+ </action>
+ <action issue="VFS-258" dev="ggregory" type="fix" due-to="mzawirski">
+ [SFTP][RAM] Unsafe casting to AbstractFileObject subclasses in doRename().
+ </action>
+ <action issue="VFS-254" dev="ggregory" type="add" due-to="mzawirski">
+ Let FileObject and FileContent extend java.io.Closeable.
+ </action>
+ <action issue="VFS-413" dev="ggregory" type="fix" due-to="polivenok">
+ [FTP] No support for FTP servers with non Latin-1 control encoding.
+ </action>
+ <action issue="VFS-252" dev="ggregory" type="add">
+ [SMB] SmbFileObject does not support setLastModifiedTime while jcifs supports it.
+ </action>
+ <action issue="VFS-200" dev="ggregory" type="fix">
+ [SFTP] Failure when files are very large.
+ </action>
+ <action issue="VFS-416" dev="joehni" type="update">
+ [SFTP] Update Jsch to version 0.1.49 from 0.1.47.
+ </action>
+ <action issue="VFS-296" dev="ggregory" type="fix" due-to="andreasp">
+ [FTP] FTP socket timeout setting doesn't work if connect hangs.
+ </action>
+ <action issue="VFS-313" dev="ggregory" type="add" due-to="bdavis@saintandreas.org">
+ [FTP] Configuration does not include option for setting socket timeout.
+ </action>
+ <action issue="VFS-414" dev="ggregory" type="add">
+ [FTP] Add config API to set the file type.
+ </action>
+ <action issue="VFS-182" dev="ggregory" type="add">
+ [FTP] Usage of FTP with heterogeneous FTP server (possibility of using Ascii file type).
+ </action>
+ <action issue="VFS-395" dev="ggregory" type="update">
+ [POM] Remove maven-scm-* dependencies.
+ </action>
+ <action issue="VFS-411" dev="ggregory" type="update">
+ [SFTP] Update Jsch to version 0.1.47 from 0.1.46.
+ </action>
+ <action issue="VFS-410" dev="ggregory" type="fix" due-to="mstockhammer">
+ [SFTP] SftpFileObject getInputStream(long) reads the whole file into memory.
+ </action>
+ <action issue="VFS-409" dev="ggregory" type="update">
+ Update Apache Commons Compress to 1.4 from 1.3.
+ </action>
+ <action issue="VFS-407" dev="ggregory" type="fix" due-to="mp1">
+ [RAM] Reading a RAM FileSystem file fails because it never returns EOF -1.
+ </action>
+ <action issue="VFS-404" dev="ggregory" type="update">
+ [FTP][FTPS] Update Apache Commons Net to 3.1 from 3.0.1.
+ </action>
+ <action issue="VFS-402" dev="ggregory" type="update">
+ [WebDAV] Update Apache Jackrabbit 1.5.2 to 1.6.5.
+ </action>
+ <action issue="VFS-401" dev="ggregory" type="update">
+ Update JSch to 0.1.46 from 0.1.45 for the SFTP provider.
+ </action>
+ <action issue="VFS-392" dev="ggregory" type="update">
+ Build tests WebDAV file system with an embedded WebDAV server (Apache Jackrabbit).
+ </action>
+ <action issue="VFS-391" dev="ggregory" type="update">
+ Build tests URL HTTP file system with an embedded HTTP server (Apache HttpComponent Core).
+ </action>
+ <action issue="VFS-390" dev="ggregory" type="update">
+ Use variable argument list in org.apache.commons.vfs2.util.Messages instead of Object[].
+ </action>
+ <action issue="VFS-389" dev="ggregory" type="update">
+ Use variable argument lists in FileSystemException instead of Object[]s.
+ </action>
+ <action issue="VFS-388" dev="ggregory" type="update">
+ Build tests SFTP file system with an embedded SFTP server (Apache MINA).
+ </action>
+ <action issue="VFS-387" dev="ggregory" type="update">
+ Build tests FTP file system with an embedded FTP server (Apache MINA).
+ </action>
+ <action issue="VFS-386" dev="ggregory" type="update">
+ Build tests HTTP file system with an embedded HTTP server (Apache HttpComponent Core).
+ </action>
+ <action issue="VFS-385" dev="ggregory" type="update">
+ Add HTTP status code to HTTP file provider exception messages when available.
+ </action>
+ <action issue="VFS-384" dev="ggregory" type="update">
+ Update Apache Commons Net to 3.0.1 from 2.2 for FTP and SFTP providers.
+ </action>
+ <action issue="VFS-383" dev="ggregory" type="update">
+ Update JSch to 0.1.45 from 0.1.42 for the SFTP provider.
+ </action>
+ <action issue="VFS-382" dev="ggregory" type="fix">
+ SFTP getChildren() does not fail when called on a file.
+ </action>
+ <action issue="VFS-381" dev="ggregory" type="add">
+ Iterate over a FileObject using the Java "foreach" statement, to provide all descendents of a FileObject.
+ </action>
+ <action issue="VFS-380" dev="ggregory" type="fix">
+ FTP connect.error message used instead of SFTP connect.error message.
+ </action>
+ <action issue="VFS-379" dev="ggregory" type="update">
+ Replace custom BZIP2 code with Apache Commons Compress 1.3.
+ </action>
+ <action issue="VFS-378" dev="ggregory" type="fix">
+ Tar error message are missing from resource file.
+ </action>
+ <action issue="VFS-377" dev="ggregory" type="update">
+ Replace custom TAR code with Apache Commons Compress 1.3.
+ </action>
+ <action issue="VFS-375" dev="ggregory" type="update">
+ Upgrade to Apache Commons Compress 1.3 from 1.2.
+ </action>
+ <action issue="VFS-374" dev="ggregory" type="fix">
+ Incorrect lazy initialization of static field org.apache.commons.vfs2.util.Messages.resources in org.apache.commons.vfs2.util.Messages.findMessage(String)Add FileContent write APIs.
+ </action>
+ <action issue="VFS-373" dev="ggregory" type="add">
+ Add FileContent write APIs.
+ </action>
+ <action issue="VFS-372" dev="ggregory" type="add">
+ Add constructors FileDepthSelector() and FileDepthSelector(int).
+ </action>
+ <action issue="VFS-371" dev="ggregory" type="add">
+ Add FileObject API deleteAll().
+ </action>
+ <action issue="VFS-370" dev="ggregory" type="add">
+ Add a FileExtensionSelector class.
+ </action>
+ <action issue="VFS-367" dev="ggregory" type="add">
+ Add APIs FileObject isFile(), FileObject isFolder(), and FileName isFile().
+ </action>
+ <action issue="VFS-366" dev="ggregory" type="update">
+ Can't sort a List of FileObject's, FileObject to implement Comparable<FileObject>.
+ </action>
+ <action issue="VFS-341" dev="rgoers" type="update" due-to="Rajika Kumarasiri">
+ Enable logging of JSch using the Commons Logging Log object in SftpClientFactory.
+ </action>
+ <action issue="VFS-355" dev="rgoers" type="fix" due-to="Miroslav Pokorny">
+ The read method of RamFileRandomAccessContent's input stream does not return -1 at eof.
+ </action>
+ <action issue="VFS-356" dev="rgoers" type="fix">
+ Throw an IOException if an attempt is made to seek to a position before the start of the file.
+ </action>
+ <action issue="VFS-359" dev="rgoers" type="fix" due-to="Miroslav Pokorny">
+ Don't delete a RamFileObject if it is open.
+ </action>
+ <action issue="VFS-352" dev="rgoers" type="fix">
+ ZipFileSystem now uses an internal Map as a cache for all the files in the zip archive.
+ </action>
+ <action issue="VFS-351" dev="rgoers" type="fix" due-to="John Backstrand">
+ Chain the SftpException in the FileSystemException.
+ </action>
+ <action issue="VFS-361" dev="rgoers" type="update">
+ Upgrade commons collections version to 3.2.1.
+ </action>
+ <action issue="VFS-325" dev="rgoers" type="fix" due-to="Larry Reeve">
+ Allow # character in file names.
+ </action>
+ <action issue="VFS-335" dev="rgoers" type="fix">
+ Use atomic variables in MonitorInputStream.
+ </action>
+ <action issue="VFS-364" dev="rgoers" type="fix">
+ Check the href in the response for just a path in addition to a full uri.
+ </action>
+ </release>
+ <release version="2.0" date="2011-08-24" description="Backwards incompatible update of Commons VFS to Java 5">
+ <action issue="VFS-348" dev="rgoers" type="fix" due-to="Stefan Bodewig">
+ Update the version of commons-net.
+ </action>
+ <action issue="VFS-230" dev="rgoers" type="fix">
+ Documented FileSystem capabilities on the web site.
+ </action>
+ <action issue="VFS-337" dev="rgoers" type="fix">
+ AbstractFileObject and classes that extend from it use AbstractFileName in the constructor and in
+ the createFile method.
+ </action>
+ <action issue="VFS-245" dev="rgoers" type="fix">
+ AbstractFileName is not immutable as it should be. equals(), hashcode() and compareTo() have been modified
+ to return the same results regardless of whether the FileType is changed.
+ </action>
+ <action issue="VFS-334" dev="sebb" type="fix">
+ DefaultFileSystemConfigBuilder.getConfigClass() returns DefaultFileSystemConfigBuilder.class which is not a FileSystem
+ </action>
+ <action dev="rgoers" type="fix" issue="VFS-305" due-to="Tom">
+ Add encoding option to FTP provider.
+ </action>
+ <action dev="rgoers" type="fix" issue="VFS-315" due-to="David Hausladen">
+ Fix potential NullPointerException if the DavProperty is null or contains null values.
+ </action>
+ <action dev="rgoers" type="fix" issue="VFS-316" due-to="David Hausladen">
+ Add option for preemptive authentication for HTTP based protocols.
+ </action>
+ <action dev="rgoers" type="fix" issue="VFS-322" due-to="Curtis Boyden">
+ Allow tar files that contain files over 2GB in size.
+ </action>
+ <action dev="rgoers" type="fix" issue="VFS-324" due-to="sebb">
+ Clear the cache in RamFileSystem and the children in RamFileData.
+ </action>
+ <action dev="sebb" type="fix" issue="VFS-319">
+ Typo in FtpsFileSystemConfigBuilder.setFtpsType
+ </action>
+ <action dev="rgoers" type="fix" issue="VFS-227" due-to="Sergey Vladimirov">
+ InputStream and RandomAccessContent memory leak in FileContentThreadData
+ </action>
+ <action dev="rgoers" type="update" issue="VFS-263" due-to="Ingo Maas">
+ WebdavFileObject does not implement doSetAttribute()
+ </action>
+ <action dev="rgoers" type="fix" issue="VFS-259" due-to="Marek Zawirski">
+ Http and Webdav FIleContentInfoFactory: undress to AbstractFileObject before casting
+ </action>
+ <action dev="rgoers" type="fix" issue="VFS-261" due-to="Simon Olofsson">
+ WebDAV upload corrupts binary files
+ </action>
+ <action dev="rgoers" type="fix" issue="VFS-276" due-to="Vince Bonfanti">
+ add ProviderTestConfig.getDefaultFileSystemManager() method
+ </action>
+ <action dev="rgoers" type="fix" issue="VFS-282" due-to="Alexey">
+ SftpFileProvider and SftpFileSystemConfigBuilder can't change ssh authentication methods
+ </action>
+ <action dev="rgoers" type="fix" issue="VFS-269" due-to="Marek Zawirski">
+ HttpFileObject: unsupported content over 2GB length
+ </action>
+ <action dev="rgoers" type="fix" issue="VFS-287" due-to="Mircea-Eugen Ionica">
+ LocalFileName objects are not released from AbstractFileSystem.listenerMap when all listeners are removed.
+ </action>
+ <action dev="rgoers" type="fix" issue="VFS-216" due-to="Reetu Mutti">
+ The FTP Configuration includes an option to set a timeout for the data connection, but not for the socket
+ timeout. This is a problem, as idle sockets can cause your download to hang forever and never timeout.
+ </action>
+ <action dev="rgoers" type="fix" issue="VFS-289" due-to="Kirill Safonov">
+ FTP connection is not released If exception is thrown out of FtpFileObject.doGetOutputStream().
+ </action>
+ <action dev="rgoers" type="fix" issue="VFS-286" due-to="Kirill Safonov">
+ SftpFileObject.doListChildrenResolved() changes the working dir before doing ChannelSftp.ls() call.
+ If ls() throws an exception, the current directory is not reset. All the subsequent operations that rely on the
+ current dir will fail trying to change into nonexistent directory.
+ </action>
+ <action dev="jcarman" type="add" issue="VFS-264" due-to="Scott Bjerstedt">
+ Add FTPS provider.
+ </action>
+ <action dev="rgoers" type="add" issue="VFS-244">
+ Rename HttpRandomAccesContent to HttpRandomAccessContent.
+ </action>
+ </release>
+ </body>
+</document>
diff --git a/trunk/src/changes/release-notes.vm b/trunk/src/changes/release-notes.vm
new file mode 100644
index 0000000..706d3c0
--- /dev/null
+++ b/trunk/src/changes/release-notes.vm
@@ -0,0 +1,122 @@
+## Licensed to the Apache Software Foundation (ASF) under one
+## or more contributor license agreements. See the NOTICE file
+## distributed with this work for additional information
+## regarding copyright ownership. The ASF licenses this file
+## to you under the Apache License, Version 2.0 (the
+## "License"); you may not use this file except in compliance
+## with the License. You may obtain a copy of the License at
+##
+## http://www.apache.org/licenses/LICENSE-2.0
+##
+## Unless required by applicable law or agreed to in writing,
+## software distributed under the License is distributed on an
+## "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+## KIND, either express or implied. See the License for the
+## specific language governing permissions and limitations
+## under the License.
+##
+ ${project.name} ${version}
+ RELEASE NOTES
+
+The ${developmentTeam} is pleased to announce the release of ${project.name} ${version}
+
+$introduction.replaceAll("(?<!\015)\012", "
+").replaceAll("(?m)^ +","")
+
+## N.B. the available variables are described here:
+## http://maven.apache.org/plugins/maven-changes-plugin/examples/using-a-custom-announcement-template.html
+##
+## Hack to improve layout: replace all pairs of spaces with a single new-line
+$release.description.replaceAll(" ", "
+")
+
+## set up indent sizes. Only change indent1
+#set($props=${project.properties})
+#set($jiralen=$props.get("commons.jira.id").length())
+## indent1 = POOL-nnnn:
+#set($blanklen=$jiralen+6)## +6 for "-nnnn:"
+## must be at least as long as the longest JIRA id
+#set($blanks=" ")
+#set($indent1=$blanks.substring(0,$blanklen))
+## indent2 allows for issue wrapper
+#set($indent2="$indent1 ")
+##
+#macro ( processaction )
+## Use replaceAll to fix up LF-only line ends on Windows.
+#set($action=$actionItem.getAction().replaceAll("\n","
+"))
+## Replace < with < so can embed tag markup
+#set($action=$action.replaceAll("<","<"))
+## use an empty date to mean don't format the entry
+## TODO how to enable leading spaces without compromising html report
+## unfortunately leading spaces are trimmed even from CDATA sections
+#if ($actionItem.getDate() && $actionItem.getDate().length()==0)
+$action
+#else
+## Fix up indentation for multi-line action descriptions
+#set($action=$action.replaceAll("(?m)^ +",$indent2))
+#if ($actionItem.getIssue())
+#set($issue="$actionItem.getIssue():")
+## Pad shorter issue numbers
+#if ($issue.length() < $indent1.length())#set ($issue="$issue ")#end
+#if ($issue.length() < $indent1.length())#set ($issue="$issue ")#end
+#if ($issue.length() < $indent1.length())#set ($issue="$issue ")#end
+#else
+#set($issue=$indent1)
+#end
+#if ($actionItem.getDueTo())
+#set($dueto=" Thanks to $actionItem.getDueTo().")
+#else
+#set($dueto="")
+#end
+o $issue ${action}$dueto
+#end
+#set($action="")
+#set($issue="")
+#set($dueto="")
+#end
+##
+#if ($release.getActions().size() == 0)
+No changes defined in this version.
+#else
+Changes in this version include:
+
+#if ($release.getActions('add').size() !=0)
+New features:
+#foreach($actionItem in $release.getActions('add'))
+#processaction()
+#end
+
+#end
+##
+#if ($release.getActions('fix').size() !=0)
+Fixed Bugs:
+#foreach($actionItem in $release.getActions('fix'))
+#processaction()
+#end
+
+#end
+##
+#if ($release.getActions('update').size() !=0)
+Changes:
+#foreach($actionItem in $release.getActions('update'))
+#processaction()
+#end
+
+#end
+##
+#if ($release.getActions('remove').size() !=0)
+Removed:
+#foreach($actionItem in $release.getActions('remove'))
+#processaction()
+#end
+#end
+## End of main loop
+#end
+
+Historical list of changes: ${project.url}changes-report.html
+
+For complete information on ${project.name}, including instructions on how to submit bug reports,
+patches, or suggestions for improvement, see the Apache ${project.name} website:
+
+${project.url}
diff --git a/trunk/src/media/vfs-logo-white.xcf b/trunk/src/media/vfs-logo-white.xcf
new file mode 100644
index 0000000..e673acb
--- /dev/null
+++ b/trunk/src/media/vfs-logo-white.xcf
Binary files differ
diff --git a/trunk/src/site/resources/download_vfs.cgi b/trunk/src/site/resources/download_vfs.cgi
new file mode 100755
index 0000000..495cde1
--- /dev/null
+++ b/trunk/src/site/resources/download_vfs.cgi
@@ -0,0 +1,4 @@
+#!/bin/sh
+# Just call the standard mirrors.cgi script. It will use download.html
+# as the input template.
+exec /www/www.apache.org/dyn/mirrors/mirrors.cgi $*
\ No newline at end of file
diff --git a/trunk/src/site/resources/images/vfs-logo-white.png b/trunk/src/site/resources/images/vfs-logo-white.png
new file mode 100644
index 0000000..0690d05
--- /dev/null
+++ b/trunk/src/site/resources/images/vfs-logo-white.png
Binary files differ
diff --git a/trunk/src/site/site.xml b/trunk/src/site/site.xml
new file mode 100644
index 0000000..4af4a54
--- /dev/null
+++ b/trunk/src/site/site.xml
@@ -0,0 +1,54 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<project name="Apache Commons VFS">
+
+ <bannerRight>
+ <name>Commons VFS</name>
+ <src>/images/vfs-logo-white.png</src>
+ <href>/index.html</href>
+ </bannerRight>
+
+ <body>
+
+ <menu name="Commons VFS" inherit="top">
+ <item name="Overview" href="/index.html"/>
+ <item name="Download and Build" href="/download.html"/>
+ <item name="Using the API" href="/api.html"/>
+ <item name="API JavaDocs" href="/apidocs/index.html"/>
+ <item name="File Systems" href="/filesystems.html"/>
+ <item name="Ant Tasks" href="/anttasks.html"/>
+ <item name="Wiki" href="http://wiki.apache.org/commons/VFS"/>
+ </menu>
+
+ <menu name="VFS Development" inherit="top">
+ <item name="Testing" href="/testing.html"/>
+ <item name="Mailing Lists" href="/mail-lists.html"/>
+ <item name="Issue Tracking" href="/issue-tracking.html"/>
+ <item name="Source Repository" href="/source-repository.html"/>
+ </menu>
+
+ <menu name="VFS Modules" inherit="top">
+ <item name="Core" href="commons-vfs2/index.html"/>
+ <item name="Examples" href="commons-vfs2-examples/index.html"/>
+ <item name="Sandbox" href="commons-vfs2-sandbox/index.html"/>
+ </menu>
+
+ <menu ref="reports"/>
+ </body>
+
+</project>
diff --git a/trunk/src/site/xdoc/anttasks.xml b/trunk/src/site/xdoc/anttasks.xml
new file mode 100644
index 0000000..4d1534f
--- /dev/null
+++ b/trunk/src/site/xdoc/anttasks.xml
@@ -0,0 +1,292 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<document>
+ <properties>
+ <title>Ant Tasks</title>
+ <author email="adammurdoch@apache.org">Adam Murdoch</author>
+ </properties>
+
+ <body>
+ <section name="Ant Tasks">
+ <p>
+ Commons VFS includes several Ant tasks that can be used
+ to create, delete, copy and move files of any supported type.
+ The tasks are:
+ </p>
+ <ul>
+ <li>
+ <a href="#V-Copy">
+ <code><v-copy></code>
+ </a>
+ .
+ Copies a set of source folders and files to a destination
+ folder.
+ </li>
+ <li>
+ <a href="#V-Delete">
+ <code><v-delete></code>
+ </a>
+ .
+ Deletes a file or folder.
+ </li>
+ <li>
+ <a href="#V-Mkdir">
+ <code><v-mkdir></code>
+ </a>
+ .
+ Creates a folder.
+ </li>
+ <li>
+ <a href="#V-Move">
+ <code><v-move></code>
+ </a>
+ .
+ Moves a set of source folders and files to a destination
+ folder.
+ </li>
+ <li>
+ <a href="#V-Sync">
+ <code><v-sync></code>
+ </a>
+ .
+ Synchronises a destination folder with a set of source
+ folder and files.
+ </li>
+ </ul>
+ <p>
+ All file name attributes support relative and absolute local
+ file names, and
+ <a href="filesystems.html">absolute URI</a>
+ .
+ File names are interpreted relative to the Ant project's base
+ directory.
+ </p>
+
+ <subsection name="Using the Tasks">
+ <p>
+ To use the Ant tasks, copy commons-vfs.jar and its
+ dependencies into the
+ <code>$ANT_HOME/lib</code>
+ directory,
+ and use the following in your Ant scipt to define the tasks:
+ </p>
+
+ <source><![CDATA[
+<taskdef resource="org/apache/commons/vfs2/tasks/tasks.properties"/>
+ ]]></source>
+
+ <p>
+ Alternatively, you can provide an explicit classpath when
+ you define the tasks:
+ </p>
+
+ <source><![CDATA[
+<taskdef resource="org/apache/commons/vfs2/tasks/tasks.properties">
+ <classpath> ... </classpath>
+</taskdef>
+ ]]></source>
+
+ <p>
+ You can also use antlib:
+ <br/>
+ <b>Notice: VFS tasks registered that way do not have te "v-" prefix.</b>
+ If you migrate to antlib simply replace "v-" by e.g. "vfs:" or whatever
+ namespace you use.
+ </p>
+
+ <source><![CDATA[
+<project ... xmlns:vfs="antlib:org.apache.commons.vfs2.tasks">
+ <target name="dosomething">
+ <vfs:copy .../>
+ </target>
+</project>
+ ]]></source>
+
+ </subsection>
+ </section>
+
+ <section name="V-Copy">
+ <p>Copies a set of files to a destination folder. Does not copy
+ source files where the destination file exists and is newer than
+ the source file. The copy task takes the following attributes:</p>
+
+ <table>
+ <tr>
+ <th>Name</th>
+ <th>Description</th>
+ <th>Required</th>
+ </tr>
+ <tr>
+ <td>destdir</td>
+ <td>The destination folder. This folder is created if it
+ does not exist.</td>
+ <td rowspan="2">One only</td>
+ </tr>
+ <tr>
+ <td>destfile</td>
+ <td>The destination file. Can only be used if there is a
+ single source file.</td>
+ </tr>
+ <tr>
+ <td>srcdir</td>
+ <td>The source folder. If used the includes and desdir
+ attributes should be specified.</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td>includes</td>
+ <td>A comma or space separated list of files. The files
+ are resolved in combination with the specified
+ srcdir attribute.</td>
+ <td>Only if srcdir is specified.</td>
+ </tr>
+ <tr>
+ <td>overwrite</td>
+ <td>Always copy files, ignoring the last-modified time of
+ the destination file.</td>
+ <td>No, default is
+ <code>false</code>
+ .
+ </td>
+ </tr>
+ <tr>
+ <td>preservelastmodified</td>
+ <td>Set the last-modified time of destination files to
+ the same value as the source files. May not be supported
+ by the destination file system.</td>
+ <td>No, default is
+ <code>true</code>
+ .
+ </td>
+ </tr>
+ <tr>
+ <td>srcdirisbase</td>
+ <td>Set whether the source directory should be used as base directory.
+ If set to true, the subdirectories of the specified directories will be copied as well.</td>
+ <td>No, default is
+ <code>false</code>
+ .
+ </td>
+ </tr>
+ <tr>
+ <td>src</td>
+ <td>A source file or folder to copy. Copies all descendents
+ of a folder.</td>
+ <td>No</td>
+ </tr>
+ </table>
+
+ <subsection name="Nested Elements">
+ <p>
+ <b>
+ <code><src></code>
+ </b>
+ </p>
+
+ <p>Defines a source file or folder to copy. It takes the
+ following attributes:</p>
+
+ <table>
+ <tr>
+ <th>Name</th>
+ <th>Description</th>
+ <th>Required</th>
+ </tr>
+ <tr>
+ <td>file</td>
+ <td>The source file.</td>
+ <td>Yes</td>
+ </tr>
+ </table>
+ </subsection>
+
+ </section>
+
+ <section name="V-Move">
+ <p>Moves a set of files to a destination folder. Has the same
+ attributes and elements as the copy task and following attributes:</p>
+ <table>
+ <tr>
+ <th>Name</th>
+ <th>Description</th>
+ <th>Required</th>
+ </tr>
+ <tr>
+ <td>tryRename</td>
+ <td>The destination folder. This folder is created if it
+ does not exist.</td>
+ <td>No, default is
+ <code>false</code>
+ </td>
+ </tr>
+ </table>
+ </section>
+
+ <section name="V-Sync">
+ <p>Synchronises a destination folder with a set of source files.
+ Has the same attributes and elements as the copy task.</p>
+ </section>
+
+ <section name="V-Delete">
+ <p>Deletes a file or folder. It takes the following attributes:</p>
+
+ <table>
+ <tr>
+ <th>Name</th>
+ <th>Description</th>
+ <th>Required</th>
+ </tr>
+ <tr>
+ <td>file</td>
+ <td>The file or folder to delete. All descendents of
+ the folder are deleted.</td>
+ <td rowspan="2">One only</td>
+ </tr>
+ <tr>
+ <td>srcdir</td>
+ <td>The source folder. If used the includes attribute
+ should be specified.</td>
+ </tr>
+ <tr>
+ <td>includes</td>
+ <td>A comma or space separated list of files. The files
+ are resolved in combination with the specified
+ srcdir attribute.</td>
+ <td>Only if srcdir is specified.</td>
+ </tr>
+ </table>
+ </section>
+
+ <section name="V-Mkdir">
+ <p>Creates a folder. It takes the following attributes:</p>
+
+ <table>
+ <tr>
+ <th>Name</th>
+ <th>Description</th>
+ <th>Required</th>
+ </tr>
+ <tr>
+ <td>dir</td>
+ <td>The folder create.</td>
+ <td>Yes</td>
+ </tr>
+ </table>
+
+ </section>
+ </body>
+</document>
diff --git a/trunk/src/site/xdoc/api.xml b/trunk/src/site/xdoc/api.xml
new file mode 100644
index 0000000..52f1a37
--- /dev/null
+++ b/trunk/src/site/xdoc/api.xml
@@ -0,0 +1,379 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<document>
+ <properties>
+ <title>Using The API</title>
+ <author email="adammurdoch@apache.org">Adam Murdoch</author>
+ </properties>
+
+ <body>
+ <section name="Using The API">
+ <p>
+ The
+ <a href="apidocs/org/apache/commons/vfs2/FileSystemManager.html">FileSystemManager</a>
+ interface provides access to Commons VFS. Using this interface
+ you can locate files and create file systems.
+ There are a
+ <a href="#Configuring Commons VFS">number of ways</a>
+ to obtain a
+ <code>FileSystemManager</code> instance.
+ The simplest is to use the static
+ <a href="apidocs/org/apache/commons/vfs2/VFS.html#getManager()">VFS.getManager()</a>
+ method, which returns the default Commons VFS implementation.
+ </p>
+
+ <p>
+ Once you have a
+ <code>FileSystemManager</code>, you can use its
+ <code>resolveFile()</code> methods to locate a file by name.
+ For example:
+ </p>
+
+ <source><![CDATA[
+FileSystemManager fsManager = VFS.getManager();
+FileObject jarFile = fsManager.resolveFile( "jar:lib/aJarFile.jar" );
+ ]]></source>
+
+ <p>
+ Each file is represented by a
+ <a href="apidocs/org/apache/commons/vfs2/FileObject.html">FileObject</a>
+ instance. Using this interface you can create or delete the
+ file, list its children, read or write its content, and so on.
+ For example:
+ </p>
+
+ <source><![CDATA[
+// Locate the Jar file
+FileSystemManager fsManager = VFS.getManager();
+FileObject jarFile = fsManager.resolveFile( "jar:lib/aJarFile.jar" );
+
+// List the children of the Jar file
+FileObject[] children = jarFile.getChildren();
+System.out.println( "Children of " + jarFile.getName().getURI() );
+for ( int i = 0; i < children.length; i++ )
+{
+ System.out.println( children[ i ].getName().getBaseName() );
+}
+ ]]></source>
+
+ <p>
+ In some cases you might want to explicitely free resources allocated by the filesystem.
+ You can do this by calling
+ <a href="apidocs/org/apache/commons/vfs2/FileSystemManager.html#closeFileSystem">VFS.getManager().closeFileSystem(fs)</a>.
+ If you use VFS as singleton (as described above) you should take care that this will close the filesystem for
+ all threads.<br />
+ In other words, do not close any globally used filesystem like the one for local files.
+ </p>
+
+ <p>
+ See the
+ <a href="apidocs/org/apache/commons/vfs2/FileObject.html">FileObject</a>
+ Javadocs for more detail.
+ </p>
+
+ <subsection name="Cache">
+ <p>
+ Commons VFS uses a <a href="apidocs/org/apache/commons/vfs2/cache/SoftRefFilesCache.html">SoftRefFilesCache</a> to release memory if a file is no longer used by the application.
+ </p>
+ <p>
+ This cache will return the same instance for a file as long as it is "strongly reachable" e.g. you
+ hold a reference to this object. If the FileObject is no longer reachable, and the jvm needs some memory,
+ it will be released.
+ </p>
+ <p>
+ There is also a internal cache of each file object avoid the need to access the network layer. Now its possible
+ to configure this behviour through the use of <a href="apidocs/org/apache/commons/vfs2/CacheStrategy.html">CacheStrategy</a>.
+ <br />
+ Do this on the DefaultFileSystemManager. For example:
+ <code>
+ ((DefaultFileSystemManager) VFS.getManager()).setCacheStrategy(CacheStrategy.ON_CALL)
+ </code>
+ </p>
+ </subsection>
+
+ <subsection name="User Authentication">
+ <p>
+ You can put the credentials into the url, but the drawback here is, that it is
+ easily possible to get access to the password.
+ </p>
+ <p>
+ To solve you can use the
+ <a href="apidocs/org/apache/commons/vfs2/UserAuthenticator.html">UserAuthenticator</a>
+ </p>
+ <p>
+ For example:
+ <code>
+ StaticUserAuthenticator auth = new StaticUserAuthenticator("domain", "username", "password");
+ FileSystemOptions opts = new FileSystemOptions();
+ DefaultFileSystemConfigBuilder.getInstance().setUserAuthenticator(opts, auth);
+
+ FileObject fo = VFS.getManager().resolveFile("smb://host/anyshare/dir", opts);
+ </code>
+ </p>
+ <p>
+ Internally the UserAuthenticator uses char arrays which will be zeroed before it is
+ freed for garbage collection.Unhappily none of the current libraries use char
+ arrays and so VFS has to create a string. Thus, the main advantage
+ of this solution - security - is lost, but hey, thats not VFS fault ;-)
+ </p>
+ <p>
+ VFS calls <code>UserAuthenticator.requestAuthentication</code> each time it
+ requires credentials, it depends on the filesystem implementation how often
+ this might be. For example, with FTP this is on every connection, in SMB/JCIFS
+ this is for EVERY OBJECT. It is up to you how long you will cache credentials
+ of if you would like to provide a "save credentials" checkbox.
+ </p>
+ </subsection>
+
+ <subsection name="Examples">
+ <p>
+ For an example of using the API, take a look at the classes
+ in the
+ <a href="apidocs/org/apache/commons/vfs2/example/package-summary.html">example</a>
+ package.
+ </p>
+ </subsection>
+
+ </section>
+
+ <section name="Configuring Commons VFS">
+ <p>
+ Commons VFS is represented using the
+ <a href="apidocs/org/apache/commons/vfs2/FileSystemManager.html">FileSystemManager</a>
+ interface. There are a number of ways to create and configure a
+ <code>FileSystemManager</code> instance.
+ </p>
+ <p>
+ The simplest method is to use the static
+ <a href="apidocs/org/apache/commons/vfs2/VFS.html#getManager()">VFS.getManager()</a>
+ method, which returns the default Commons VFS implementation.
+ </p>
+ <p>
+ This method will also automatically scan the classpath for a /META-INF/vfs-providers.xml file
+ (also in jar files).
+ If such a file is found Commons VFS uses it in <u>addition</u> to the default providers.xml.
+ This allows you to start using a new filesystem by simply drop its implementation into the classpath.
+ The configuration file format is described below.<br />
+ <b>Notice:</b> Currently it is not allowed to override a already configured filesystem. Commons VFS throws
+ an exception if there is already a filesystem for a scheme.
+ </p>
+
+ <p>
+ To configure Commons VFS programatically, you can create an
+ instance of
+ <a href="apidocs/org/apache/commons/vfs2/impl/DefaultFileSystemManager.html">DefaultFileSystemManager</a>
+ and configure it manually. The default constructor
+ <code>DefaultFileSystemManager</code> creates a manager that
+ is completely empty. You will have to add file providers to it
+ to make it do anything useful.
+ </p>
+ <p>
+ Here are the steps for using
+ <code>DefaultFileSystemManager</code>:
+ </p>
+ <ol>
+ <li>Create a new instance.</li>
+ <li>
+ Set the logger for the manager and all its components,
+ using
+ <code>setLogger()</code>. This step is
+ optional, and if skipped, the manager will use the default
+ logger provided by Commons Logging.
+ </li>
+ <li>
+ Add file providers, using
+ <code>addProvider()</code>.
+ </li>
+ <li>
+ Set the default provider, using
+ <code>setDefaultProvider()</code>. This step is optional.
+ See
+ <a href="apidocs/org/apache/commons/vfs2/provider/url/UrlFileProvider.html">UrlFileProvider</a>
+ for a useful default provider.
+ </li>
+ <li>
+ Set the file replicator, using
+ <code>setReplicator()</code>.
+ This step is optional.
+ </li>
+ <li>
+ Set the temporary file store, using
+ <code>setTemporaryFileStore()</code>.
+ This step is optional.
+ </li>
+ <li>
+ Set the base file using
+ <code>setBaseFile()</code>. The
+ base file is used to resolve relative URI passed to
+ <code>resolveFile()</code>. This step is optional.
+ </li>
+ <li>
+ Initialise the manager using
+ <code>init()</code>.
+ </li>
+ </ol>
+ <p>
+ You should make sure that you call
+ <code>close()</code> on the
+ manager when you are finished with it.
+ </p>
+
+ <p>
+ The third method for configuring Commons VFS, is to configure
+ it from a file. Create an instance of
+ <a href="apidocs/org/apache/commons/vfs2/impl/StandardFileSystemManager.html">StandardFileSystemManager</a>,
+ and use its
+ <code>setConfiguration()</code> method to set the
+ location of the configuration file to use. The configuration
+ file format is described below.
+ </p>
+
+ <p>
+ <code>StandardFileSystemManager</code> is a subclass of
+ <code>DefaultFileSystemManager</code>, so you can also
+ configure it programmatically, as described above.
+ </p>
+ <subsection name="Configuration File">
+ <p>
+ The configuration file is an XML file. The root element
+ of the configuration file should be a
+ <code><providers></code> element.
+ The
+ <code><providers></code> element may contain:
+ </p>
+ <ul>
+ <li>Zero or more
+ <code><provider></code> elements.
+ </li>
+ <li>An optional
+ <code><default-provider></code> element.
+ </li>
+ <li>Zero or more
+ <code><extension-map></code> elements.
+ </li>
+ <li>Zero or more
+ <code><mime-type-map></code> elements.
+ </li>
+ </ul>
+
+ <p>
+ <b>
+ <code><provider></code>
+ </b>
+ </p>
+ <p>
+ The
+ <code><provider></code> element defines a file
+ provider. It must have a
+ <code>class-name</code> attribute,
+ which specifies the fully-qualified name of the provider
+ class. The provider class must be public, and must have a
+ public constructor with an FileSystemManager argument which
+ allows the systems to pass the used filesystem manager.
+ </p>
+ <p>
+ The
+ <code><provider></code> element may contain
+ zero or more
+ <code><scheme></code> elements,
+ and zero or more
+ <code><if-available></code> elements.
+ </p>
+ <p>
+ The
+ <code><scheme></code> element defines a URI scheme
+ that the provider will handle. It must have a
+ <code>name</code> attribute, which specifies the URI scheme.
+ </p>
+ <p>
+ The
+ <code><if-available></code> elements is used to
+ disable the provider if certain classes are not present in
+ the class-path.
+ It must have a
+ <code>class-name</code> attribute, which
+ specifies the fully qualified name of a class to test for.
+ If the class cannot be found, the provider is not registered.
+ </p>
+
+ <p>
+ <b>
+ <code><default-provider></code>
+ </b>
+ </p>
+ <p>
+ The
+ <code><default-provider></code> element defines
+ the default provider. It has the same format as the
+ <code><provider></code> element.
+ </p>
+
+ <p>
+ <b>
+ <code><extension-map></code>
+ </b>
+ </p>
+ <p>
+ The
+ <code><extension-map></code> element defines
+ a mapping from a file's extension to the provider that
+ should handle files with that extension.
+ It must have an
+ <code>extension</code> attribute, which
+ specifies the extension, and a
+ <code>scheme</code> attribute,
+ which specifies the URI scheme of the provider.
+ </p>
+
+ <p>
+ <b>
+ <code><mime-type-map></code>
+ </b>
+ </p>
+ <p>
+ The
+ <code><mime-type-map></code> element defines
+ a mapping from a file's MIME type to the provider that
+ should handle files with that MIME type.
+ It must have an
+ <code>mime-type</code> attribute, which
+ specifies the MIME type, and a
+ <code>scheme</code> attribute,
+ which specified the URI scheme of the provider.
+ </p>
+
+ <p>
+ Below is an example configuration file:
+ </p>
+ <source><![CDATA[
+<providers>
+ <provider class-name="org.apache.commons.vfs2.provider.zip.ZipFileProvider">
+ <scheme name="zip"/>
+ </provider>
+ <extension-map extension="zip" scheme="zip"/>
+ <mime-type-map mime-type="application/zip" scheme="zip"/>
+ <provider class-name="org.apache.commons.vfs2.provider.ftp.FtpFileProvider">
+ <scheme name="ftp"/>
+ <if-available class-name="org.apache.commons.net.ftp.FTPFile"/>
+ </provider>
+ <default-provider class-name="org.apache.commons.vfs2.provider.url.UrlFileProvider"/>
+</providers>
+ ]]></source>
+ </subsection>
+ </section>
+ </body>
+</document>
diff --git a/trunk/src/site/xdoc/download.xml b/trunk/src/site/xdoc/download.xml
new file mode 100644
index 0000000..b61845c
--- /dev/null
+++ b/trunk/src/site/xdoc/download.xml
@@ -0,0 +1,166 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<document>
+
+ <properties>
+ <title>Download</title>
+ <author email="dev@commons.apache.org">Apache Commons Developers</author>
+ </properties>
+
+ <body>
+ <section name="Download">
+ <p>
+ The latest release (binaries and source) of Commons VFS can be found
+ <a href="download_vfs.cgi">here</a>.
+ </p>
+ <p>
+ You will also need to download the <a href="commons-vfs2/dependencies.html">dependencies</a> (jars) used by Apache Commons VFS.
+ You can download the jars from the list below; with Apache Maven dependency resolution is automatic.
+ </p>
+ <table>
+ <tr>
+ <th>Dependency</th>
+ <th>Required For</th>
+ </tr>
+ <tr>
+ <td>
+ <a href="http://commons.apache.org/logging/">Commons Logging</a>
+ Version 1.2.
+ </td>
+ <td>All</td>
+ </tr>
+ <tr>
+ <td>
+ <a href="http://commons.apache.org/collections/">Commons Collections</a>
+ Version 4.0.
+ </td>
+ <td>LRU Cache (optional)</td>
+ </tr>
+ <tr>
+ <td>
+ <a href="http://commons.apache.org/compress/">Commons Compress</a>
+ Version 1.9.
+ </td>
+ <td>TAR, Bzip2</td>
+ </tr>
+ <tr>
+ <td>
+ <a href="http://commons.apache.org/net/">Commons Net</a>
+ Version 3.3.
+ </td>
+ <td>FTP</td>
+ </tr>
+ <tr>
+ <td>
+ <a href="http://commons.apache.org/httpclient/">Commons Httpclient</a>
+ Version 3.1.<br/>
+ Requires <a href="http://commons.apache.org/proper/commons-codec/">Commons Codec</a> Version 1.2.
+ </td>
+ <td>WebDAV, HTTP, URI Utils</td>
+ </tr>
+ <tr>
+ <td>
+ <a href="http://jackrabbit.apache.org/jackrabbit-webdav-library.html">Apache Jackrabbit WebDAV Library</a>
+ Version 1.6.5.<br/>
+ Requires <a href="http://jackrabbit.apache.org/jackrabbit-jcr-commons.html">Jackrabbit JCR Commons</a>
+ Version 1.6.5 and <a href="http://www.slf4j.org">SLF4J</a>
+ Version 1.5.3 (Api and Impl).
+ </td>
+ <td>WebDAV</td>
+ </tr>
+ <tr>
+ <td>
+ <a href="http://www.jcraft.com/jsch/">JSch</a>
+ Version 0.1.51.
+ </td>
+ <td>SFTP</td>
+ </tr>
+ <tr>
+ <td>
+ <a href="http://hadoop.apache.org/docs/stable/">Apache Hadoop Common</a>
+ Version 2.6.0.<br/>
+ <a href="http://hadoop.apache.org/docs/stable/">Apache Hadoop HDFS Common</a>
+ Version 2.6.0<br/>
+ This requires a number of dependencies, use <code>$HADOOP_HOME/bin/hadoop classpath</code> command.
+ </td>
+ <td>hdfs</td>
+ </tr>
+ <tr>
+ <td>
+ <a href="http://jcifs.samba.org/">jCIFS</a>
+ Version 0.8.3.
+ </td>
+ <td>CIFS (VFS sandbox)</td>
+ </tr>
+ <tr>
+ <td>
+ <a href="http://java.sun.com/products/javamail/">javamail</a>
+ Version 1.4.7.
+ </td>
+ <td>mime (VFS sandbox)</td>
+ </tr>
+ </table>
+ </section>
+ <section name="Obtaining Commons VFS source">
+ <p>
+ To obtain the Commons VFS source, you can either:
+ </p>
+ <ul>
+ <li>
+ The primary source repository for the Apache Commons VFS project is the
+ <em>Subversion</em> repository. You can use the following command to check out
+ the latest source version:
+ <br/>
+ <code>svn co http://svn.apache.org/repos/asf/commons/proper/vfs/trunk commons-vfs</code><br/>
+ <br/>
+ For a certain version please look at
+ <a href="http://svn.apache.org/repos/asf/commons/proper/vfs/tags">
+ http://svn.apache.org/repos/asf/commons/proper/vfs/tags</a>
+ </li>
+ <li>
+ If you prefer <em>Git</em>, you can get the sources from the Apache Git mirror:<br/>
+ <br/>
+ <code>git clone git://git.apache.org/commons-vfs.git commons-vfs</code><br/>
+ <br/>
+ There is also a guideline for <a href="https://github.com/apache/commons-vfs/blob/trunk/CONTRIBUTING.md">contributing via GitHub</a>.
+ </li>
+ <li>
+ Obtain the source from the latest release distribution. See the <a href="download_vfs.cgi">downloads</a> page.
+ </li>
+ </ul>
+ </section>
+ <section name="Building Commons VFS">
+ <p>
+ To build Commons VFS, you can use <a href="http://maven.apache.org">Maven</a> 3.0.5 or later.
+ You need to use Java 6 or later (tested with Java 6 - 8). Production builds are done with the
+ <code>-Pjava-1.6</code> profile from Commons Parent (which will compile and test with a JDK
+ from the JAVA_1_6_HOME environment variable).
+ </p><p>
+ Use <code>mvn clean verify</code> to locally build and test the <code>core</code> and
+ <code>examples</code> modules. This will build the core JAR files in
+ <code>commons-vfs/core/target/commons-vfs2-<version>.jar</code>.
+ </p><p>
+ If you want to build the additional sandbox file systems as well, use
+ <code>mvn -Pinclude-sandbox clean verify</code>. This will also create the sandbox
+ components in <code>commons-vfs/sandbox/target/commons-vfs2-sandbox-<version>.jar</code>.
+ </p><p>
+ See the <a href="commons-vfs2-example/index.html">commons-vfs2-example</a> Module on how
+ to use VFS Example Shell to verify the result.
+ </p>
+ </section>
+ </body>
+</document>
diff --git a/trunk/src/site/xdoc/download_vfs.xml b/trunk/src/site/xdoc/download_vfs.xml
new file mode 100644
index 0000000..0bdb73e
--- /dev/null
+++ b/trunk/src/site/xdoc/download_vfs.xml
@@ -0,0 +1,182 @@
+<?xml version="1.0"?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements. See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to You under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+-->
+<!--
+ +======================================================================+
+ |**** ****|
+ |**** THIS FILE IS GENERATED BY THE COMMONS BUILD PLUGIN ****|
+ |**** DO NOT EDIT DIRECTLY ****|
+ |**** ****|
+ +======================================================================+
+ | TEMPLATE FILE: download-page-template.xml |
+ | commons-build-plugin/trunk/src/main/resources/commons-xdoc-templates |
+ +======================================================================+
+ | |
+ | 1) Re-generate using: mvn commons:download-page |
+ | |
+ | 2) Set the following properties in the component's pom: |
+ | - commons.componentid (required, alphabetic, lower case) |
+ | - commons.release.version (required) |
+ | - commons.release.name (required) |
+ | - commons.binary.suffix (optional) |
+ | (defaults to "-bin", set to "" for pre-maven2 releases) |
+ | - commons.release.desc (optional) |
+ | |
+ | - commons.release.2/3.version (conditional) |
+ | - commons.release.2/3.name (conditional) |
+ | - commons.release.2/3.binary.suffix (optional) |
+ | - commons.release.2/3.desc (optional) |
+ | |
+ | 3) Example Properties |
+ | (commons.release.name inherited by parent: |
+ | ${project.artifactId}-${commons.release.version} |
+ | |
+ | <properties> |
+ | <commons.componentid>math</commons.componentid> |
+ | <commons.release.version>1.2</commons.release.version> |
+ | </properties> |
+ | |
+ +======================================================================+
+-->
+<document>
+ <properties>
+ <title>Download Apache Commons VFS</title>
+ <author email="dev@commons.apache.org">Apache Commons Documentation Team</author>
+ </properties>
+ <body>
+ <section name="Download Apache Commons VFS">
+ <subsection name="Using a Mirror">
+ <p>
+ We recommend you use a mirror to download our release
+ builds, but you <strong>must</strong> <a href="https://www.apache.org/info/verification.html">verify the integrity</a> of
+ the downloaded files using signatures downloaded from our main
+ distribution directories. Recent releases (48 hours) may not yet
+ be available from all the mirrors.
+ </p>
+
+ <p>
+ You are currently using <b>[preferred]</b>. If you
+ encounter a problem with this mirror, please select another
+ mirror. If all mirrors are failing, there are <i>backup</i>
+ mirrors (at the end of the mirrors list) that should be
+ available.
+ <br></br>
+ [if-any logo]<a href="[link]"><img align="right" src="[logo]" border="0"></img></a>[end]
+ </p>
+
+ <form action="[location]" method="get" id="SelectMirror">
+ <p>
+ Other mirrors:
+ <select name="Preferred">
+ [if-any http]
+ [for http]<option value="[http]">[http]</option>[end]
+ [end]
+ [if-any ftp]
+ [for ftp]<option value="[ftp]">[ftp]</option>[end]
+ [end]
+ [if-any backup]
+ [for backup]<option value="[backup]">[backup] (backup)</option>[end]
+ [end]
+ </select>
+ <input type="submit" value="Change"></input>
+ </p>
+ </form>
+
+ <p>
+ It is essential that you
+ <a href="https://www.apache.org/info/verification.html">verify the integrity</a>
+ of downloaded files, preferably using the <code>PGP</code> signature (<code>*.asc</code> files);
+ failing that using the <code>MD5</code> hash (<code>*.md5</code> checksum files).
+ </p>
+ <p>
+ The <a href="https://www.apache.org/dist/commons/KEYS">KEYS</a>
+ file contains the public PGP keys used by Apache Commons developers
+ to sign releases.
+ </p>
+ </subsection>
+ </section>
+ <section name="Apache Commons VFS 2.1 (requires Java 1.6+)">
+ <subsection name="Binaries">
+ <table>
+ <tr>
+ <td><a href="[preferred]/commons/vfs/binaries/commons-vfs-2.1.tar.gz">commons-vfs-2.1.tar.gz</a></td>
+ <td><a href="https://www.apache.org/dist/commons/vfs/binaries/commons-vfs-2.1.tar.gz.md5">md5</a></td>
+ <td><a href="https://www.apache.org/dist/commons/vfs/binaries/commons-vfs-2.1.tar.gz.asc">pgp</a></td>
+ </tr>
+ <tr>
+ <td><a href="[preferred]/commons/vfs/binaries/commons-vfs-2.1.zip">commons-vfs-2.1.zip</a></td>
+ <td><a href="https://www.apache.org/dist/commons/vfs/binaries/commons-vfs-2.1.zip.md5">md5</a></td>
+ <td><a href="https://www.apache.org/dist/commons/vfs/binaries/commons-vfs-2.1.zip.asc">pgp</a></td>
+ </tr>
+ </table>
+ </subsection>
+ <subsection name="Source">
+ <table>
+ <tr>
+ <td><a href="[preferred]/commons/vfs/source/commons-vfs-2.1-src.tar.gz">commons-vfs-2.1-src.tar.gz</a></td>
+ <td><a href="https://www.apache.org/dist/commons/vfs/source/commons-vfs-2.1-src.tar.gz.md5">md5</a></td>
+ <td><a href="https://www.apache.org/dist/commons/vfs/source/commons-vfs-2.1-src.tar.gz.asc">pgp</a></td>
+ </tr>
+ <tr>
+ <td><a href="[preferred]/commons/vfs/source/commons-vfs-2.1-src.zip">commons-vfs-2.1-src.zip</a></td>
+ <td><a href="https://www.apache.org/dist/commons/vfs/source/commons-vfs-2.1-src.zip.md5">md5</a></td>
+ <td><a href="https://www.apache.org/dist/commons/vfs/source/commons-vfs-2.1-src.zip.asc">pgp</a></td>
+ </tr>
+ </table>
+ </subsection>
+ </section>
+ <section name="Apache Commons VFS 2.0 (requires Java 1.5+)">
+ <subsection name="Binaries">
+ <table>
+ <tr>
+ <td><a href="[preferred]/commons/vfs/binaries/commons-vfs-2.0.tar.gz">commons-vfs-2.0.tar.gz</a></td>
+ <td><a href="https://www.apache.org/dist/commons/vfs/binaries/commons-vfs-2.0.tar.gz.md5">md5</a></td>
+ <td><a href="https://www.apache.org/dist/commons/vfs/binaries/commons-vfs-2.0.tar.gz.asc">pgp</a></td>
+ </tr>
+ <tr>
+ <td><a href="[preferred]/commons/vfs/binaries/commons-vfs-2.0.zip">commons-vfs-2.0.zip</a></td>
+ <td><a href="https://www.apache.org/dist/commons/vfs/binaries/commons-vfs-2.0.zip.md5">md5</a></td>
+ <td><a href="https://www.apache.org/dist/commons/vfs/binaries/commons-vfs-2.0.zip.asc">pgp</a></td>
+ </tr>
+ </table>
+ </subsection>
+ <subsection name="Source">
+ <table>
+ <tr>
+ <td><a href="[preferred]/commons/vfs/source/commons-vfs-2.0-src.tar.gz">commons-vfs-2.0-src.tar.gz</a></td>
+ <td><a href="https://www.apache.org/dist/commons/vfs/source/commons-vfs-2.0-src.tar.gz.md5">md5</a></td>
+ <td><a href="https://www.apache.org/dist/commons/vfs/source/commons-vfs-2.0-src.tar.gz.asc">pgp</a></td>
+ </tr>
+ <tr>
+ <td><a href="[preferred]/commons/vfs/source/commons-vfs-2.0-src.zip">commons-vfs-2.0-src.zip</a></td>
+ <td><a href="https://www.apache.org/dist/commons/vfs/source/commons-vfs-2.0-src.zip.md5">md5</a></td>
+ <td><a href="https://www.apache.org/dist/commons/vfs/source/commons-vfs-2.0-src.zip.asc">pgp</a></td>
+ </tr>
+ </table>
+ </subsection>
+ </section>
+ <section name="Archives">
+ <p>
+ Older releases can be obtained from the archives.
+ </p>
+ <ul>
+ <li class="download"><a href="[preferred]/commons/vfs/">browse download area</a></li>
+ <li><a href="https://archive.apache.org/dist/commons/vfs/">archives...</a></li>
+ </ul>
+ </section>
+ </body>
+</document>
diff --git a/trunk/src/site/xdoc/filesystems.xml b/trunk/src/site/xdoc/filesystems.xml
new file mode 100644
index 0000000..e0d0559
--- /dev/null
+++ b/trunk/src/site/xdoc/filesystems.xml
@@ -0,0 +1,854 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<document>
+
+ <properties>
+ <title>Supported File Systems</title>
+ <author email="dev@commons.apache.org">Apache Commons Developers</author>
+ </properties>
+
+ <body>
+ <section name="Supported File Systems">
+ <p>Commons VFS directly supports the following file systems with the listed
+ <a href="apidocs/org/apache/commons/vfs2/Capability.html">capabilities</a>:</p>
+ <table>
+ <tr>
+ <th>File System</th>
+ <th>Directory Contents</th>
+ <th>Authentication</th>
+ <th>Read</th>
+ <th>Write</th>
+ <th>Create/Delete</th>
+ <th>Random</th>
+ <th>Version</th>
+ <th>Rename</th>
+ </tr>
+ <tr>
+ <td><a href="#gzip and bzip2">BZIP2</a></td>
+ <td>No</td>
+ <td>No</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>No</td>
+ <td>No</td>
+ <td>No</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td><a href="#Local Files">File</a></td>
+ <td>No</td>
+ <td>No</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Read/Write</td>
+ <td>No</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td><a href="#FTP">FTP</a></td>
+ <td>No</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Read</td>
+ <td>No</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td><a href="#FTPS">FTPS</a></td>
+ <td>No</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Read</td>
+ <td>No</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td><a href="#gzip and bzip2">GZIP</a></td>
+ <td>No</td>
+ <td>No</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>No</td>
+ <td>No</td>
+ <td>No</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td><a href="#HDFS">HDFS</a></td>
+ <td>Yes</td>
+ <td>No</td>
+ <td>Yes</td>
+ <td>No</td>
+ <td>No</td>
+ <td>Read</td>
+ <td>No</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td><a href="#HTTP and HTTPS">HTTP</a></td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>No</td>
+ <td>No</td>
+ <td>Read</td>
+ <td>No</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td><a href="#HTTP and HTTPS">HTTPS</a></td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>No</td>
+ <td>No</td>
+ <td>Read</td>
+ <td>No</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td><a href="#Zip, Jar and Tar">Jar</a></td>
+ <td>No</td>
+ <td>No</td>
+ <td>Yes</td>
+ <td>No</td>
+ <td>No</td>
+ <td>No</td>
+ <td>No</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td><a href="#ram">RAM</a></td>
+ <td>No</td>
+ <td>No</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Read/Write</td>
+ <td>No</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td><a href="#res">RES</a></td>
+ <td>No</td>
+ <td>No</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Read/Write</td>
+ <td>No</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td><a href="#SFTP">SFTP</a></td>
+ <td>No</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Read</td>
+ <td>No</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td><a href="#Zip, Jar and Tar">Tar</a></td>
+ <td>No</td>
+ <td>No</td>
+ <td>Yes</td>
+ <td>No</td>
+ <td>No</td>
+ <td>No</td>
+ <td>No</td>
+ <td>No</td>
+ </tr>
+ <tr>
+ <td><a href="#Temporary Fils">Temp</a></td>
+ <td>No</td>
+ <td>No</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Read/Write</td>
+ <td>No</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td><a href="WebDAV">WebDAV</a></td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Read/Write</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td><a href="#Zip, Jar and Tar">Zip</a></td>
+ <td>No</td>
+ <td>No</td>
+ <td>Yes</td>
+ <td>No</td>
+ <td>No</td>
+ <td>No</td>
+ <td>No</td>
+ <td>No</td>
+ </tr>
+ </table>
+ </section>
+
+ <section name="Things from the sandbox">
+ <p>The following file systems are in development:</p>
+ <table>
+ <tr>
+ <th>File System</th>
+ <th>Directory Contents</th>
+ <th>Authentication</th>
+ <th>Read</th>
+ <th>Write</th>
+ <th>Create/Delete</th>
+ <th>Random</th>
+ <th>Version</th>
+ <th>Rename</th>
+ </tr>
+ <tr>
+ <td><a href="#CIFS">CIFS</a></td>
+ <td>No</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Yes</td>
+ <td>Read/Write</td>
+ <td>No</td>
+ <td>Yes</td>
+ </tr>
+ <tr>
+ <td><a href="#mime">mime</a></td>
+ <td>No</td>
+ <td>No</td>
+ <td>Yes</td>
+ <td>No</td>
+ <td>No</td>
+ <td>No</td>
+ <td>No</td>
+ <td>No</td>
+ </tr>
+ </table>
+ </section>
+
+ <section name="Naming">
+
+ <p>All filenames are treated as URIs. One of the consequences of this is you have to encode the '%'
+ character using <code>%25</code>. <br />
+ Depending on the filesystem additional characters are encoded if needed. This is done automatically, but
+ might be reflected in the filename.
+ </p>
+
+ <p>
+ <b>Examples</b>
+ </p>
+ <ul>
+ <li>
+ <code>file:///somedir/some%25file.txt</code>
+ </li>
+ </ul>
+ <p>
+ Many file systems accept a userid and password as part of the url. However, storing
+ a password in clear text in a file is usually unacceptable. To help with that
+ Commons VFS provides a mechanism to encrypt the password. It should be noted though,
+ that this is not completely secure since the password needs to be unencrypted
+ before Commons VFS can use it.
+ </p>
+ <p>
+ To create an encrypted password do:
+ </p>
+ <code> java -cp commons-vfs-2.0.jar org.apache.commons.vfs2.util.EncryptUtil encrypt mypassword
+ </code>
+ <p>
+ where <i>mypassword</i> is the password you want to encrypt. The result of this will be a
+ single line of output containing uppercase hex characters. For example,
+ </p>
+ <code>
+ java -cp commons-vfs-2.0.jar org.apache.commons.vfs2.util.EncryptUtil encrypt WontUBee9
+ D7B82198B272F5C93790FEB38A73C7B8
+ </code>
+ <p>
+ Then cut the output returned and paste it into the URL as:
+ </p>
+ <code>
+ https://testuser:{D7B82198B272F5C93790FEB38A73C7B8}@myhost.com/svn/repos/vfstest/trunk
+ </code>
+ <p>
+ VFS treats a password enclosed in {} as being encrypted and will decrypt the password
+ before using it.
+ </p>
+ </section>
+
+ <section name="Local Files">
+
+ <p>Provides access to the files on the local physical file system.</p>
+
+ <p>
+ <b>URI Format</b>
+ </p>
+
+ <p>
+ <code>[file://]
+ <i>absolute-path</i>
+ </code>
+ </p>
+
+ <p>
+ Where
+ <code>
+ <i>absolute-path</i>
+ </code> is a valid absolute
+ file name for the local platform. UNC names are supported
+ under Windows.
+ </p>
+
+ <p>
+ <b>Examples</b>
+ </p>
+ <ul>
+ <li>
+ <code>file:///home/someuser/somedir</code>
+ </li>
+ <li>
+ <code>file:///C:/Documents and Settings</code>
+ </li>
+ <li>
+ <code>file://///somehost/someshare/afile.txt</code>
+ </li>
+ <li>
+ <code>/home/someuser/somedir</code>
+ </li>
+ <li>
+ <code>c:\program files\some dir</code>
+ </li>
+ <li>
+ <code>c:/program files/some dir</code>
+ </li>
+ </ul>
+ </section>
+
+ <section name="Zip, Jar and Tar">
+
+ <p>Provides read-only access to the contents of Zip, Jar and Tar files.</p>
+
+ <p>
+ <b>URI Format</b>
+ </p>
+
+ <p>
+ <code>zip://
+ <i>arch-file-uri</i>[!
+ <i>absolute-path</i>]
+ </code>
+ </p>
+ <p>
+ <code>jar://
+ <i>arch-file-uri</i>[!
+ <i>absolute-path</i>]
+ </code>
+ </p>
+ <p>
+ <code>tar://
+ <i>arch-file-uri</i>[!
+ <i>absolute-path</i>]
+ </code>
+ </p>
+ <p>
+ <code>tgz://
+ <i>arch-file-uri</i>[!
+ <i>absolute-path</i>]
+ </code>
+ </p>
+ <p>
+ <code>tbz2://
+ <i>arch-file-uri</i>[!
+ <i>absolute-path</i>]
+ </code>
+ </p>
+
+ <p>
+ Where
+ <code>arch-file-uri</code> refers to a file of any
+ supported type, including other zip files. Note: if you would like
+ to use the ! as normal character it must be escaped
+ using <code>%21</code>.<br />
+ <code>tgz</code> and <code>tbz2</code> are convenience for <code>tar:gz</code> and <code>tar:bz2</code>.
+ </p>
+
+ <p>
+ <b>Examples</b>
+ </p>
+ <ul>
+ <li>
+ <code>jar:../lib/classes.jar!/META-INF/manifest.mf</code>
+ </li>
+ <li>
+ <code>zip:http://somehost/downloads/somefile.zip</code>
+ </li>
+ <li>
+ <code>jar:zip:outer.zip!/nested.jar!/somedir</code>
+ </li>
+ <li>
+ <code>jar:zip:outer.zip!/nested.jar!/some%21dir</code>
+ </li>
+ <li>
+ <code>tar:gz:http://anyhost/dir/mytar.tar.gz!/mytar.tar!/path/in/tar/README.txt</code>
+ </li>
+ <li>
+ <code>tgz:file://anyhost/dir/mytar.tgz!/somepath/somefile</code>
+ </li>
+ </ul>
+
+ </section>
+
+ <section name="gzip and bzip2">
+
+ <p>Provides read-only access to the contents of gzip and bzip2 files.</p>
+
+ <p>
+ <b>URI Format</b>
+ </p>
+
+ <p>
+ <code>gz://
+ <i>compressed-file-uri</i>
+ </code>
+ </p>
+ <p>
+ <code>bz2://
+ <i>compressed-file-uri</i>
+ </code>
+ </p>
+
+ <p>
+ Where
+ <code>compressed-file-uri</code> refers to a file of any
+ supported type. There is no need to add a <code>!</code> part to the URI if
+ you read the content of the file you always will get the uncompressed
+ version.
+ </p>
+
+ <p>
+ <b>Examples</b>
+ </p>
+ <ul>
+ <li>
+ <code>gz:/my/gz/file.gz</code>
+ </li>
+ </ul>
+
+ </section>
+
+ <section name="HDFS">
+
+ <p>
+ Provides (read-only) access to files in an Apache Hadoop File System (HDFS).
+ On Windows the <a href="testing.html">integration test</a> is disabled by default, as it
+ requires binaries.
+ </p>
+
+ <p>
+ <b>URI Format</b>
+ </p>
+
+ <p>
+ <code>hdfs://
+ <i>hostname</i>[:
+ <i>port</i>][
+ <i>absolute-path</i>]
+ </code>
+ </p>
+
+ <p>
+ <b>Examples</b>
+ </p>
+ <ul>
+ <li>
+ <code>hdfs://somehost:8080/downloads/some_dir</code>
+ </li>
+ <li>
+ <code>hdfs://somehost:8080/downloads/some_file.ext</code>
+ </li>
+ </ul>
+ </section>
+
+ <section name="HTTP and HTTPS">
+
+ <p>Provides access to files on an HTTP server.</p>
+
+ <p>
+ <b>URI Format</b>
+ </p>
+
+ <p>
+ <code>http://[
+ <i>username</i>[:
+ <i>password</i>]@]
+ <i>hostname</i>[:
+ <i>port</i>][
+ <i>absolute-path</i>]
+ </code>
+ </p>
+ <p>
+ <code>https://[
+ <i>username</i>[:
+ <i>password</i>]@]
+ <i>hostname</i>[:
+ <i>port</i>][
+ <i>absolute-path</i>]
+ </code>
+ </p>
+ <p>
+ <b>File System Options</b>
+ <ul>
+ <li><b>proxyHost</b> The proxy host to connect through.</li>
+ <li><b>proxyPort</b> The proxy port to use.</li>
+ <li><b>cookies</b> An array of Cookies to add to the request.</li>
+ <li><b>maxConnectionsPerHost</b> The maximum number of connections allowed to
+ a specific host and port. The default is 5.</li>
+ <li><b>maxTotalConnections</b> The maximum number of connections allowed to
+ all hosts. The default is 50.</li>
+ </ul>
+ </p>
+
+ <p>
+ <b>Examples</b>
+ </p>
+ <ul>
+ <li>
+ <code>http://somehost:8080/downloads/somefile.jar</code>
+ </li>
+ <li>
+ <code>http://myusername@somehost/index.html</code>
+ </li>
+ </ul>
+ </section>
+
+ <section name="WebDAV">
+
+ <p>Provides access to files on a WebDAV server.</p>
+
+ <p>
+ <b>URI Format</b>
+ </p>
+
+ <p>
+ <code>webdav://[
+ <i>username</i>[:
+ <i>password</i>]@]
+ <i>hostname</i>[:
+ <i>port</i>][
+ <i>absolute-path</i>]
+ </code>
+ </p>
+
+ <p>
+ <b>File System Options</b>
+ <ul>
+ <li><b>versioning</b> true if versioning should be enabled</li>
+ <li><b>creatorName</b> the user name to be identified with changes to a file. If
+ not set the user name used to authenticate will be used.</li>
+ </ul>
+ </p>
+
+ <p>
+ <b>Examples</b>
+ </p>
+ <ul>
+ <li>
+ <code>webdav://somehost:8080/dist</code>
+ </li>
+ </ul>
+ </section>
+
+ <section name="FTP">
+
+ <p>Provides access to the files on an FTP server.</p>
+
+ <p>
+ <b>URI Format</b>
+ </p>
+
+ <p>
+ <code>ftp://[
+ <i>username</i>[:
+ <i>password</i>]@]
+ <i>hostname</i>[:
+ <i>port</i>][
+ <i>relative-path</i>]
+ </code>
+ </p>
+
+ <p>
+ <b>Examples</b>
+ </p>
+ <ul>
+ <li>
+ <code>ftp://myusername:mypassword@somehost/pub/downloads/somefile.tgz</code>
+ </li>
+ </ul>
+
+ <p>
+ By default, the path is relative to the user's home directory. This can be changed with:
+ </p>
+ <p>
+ <code>FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(options, false);</code>
+ </p>
+
+ </section>
+
+ <section name="FTPS">
+
+ <p>Provides access to the files on an FTP server over SSL.</p>
+
+ <p>
+ <b>URI Format</b>
+ </p>
+
+ <p>
+ <code>ftps://[
+ <i>username</i>[:
+ <i>password</i>]@]
+ <i>hostname</i>[:
+ <i>port</i>][
+ <i>absolute-path</i>]
+ </code>
+ </p>
+
+ <p>
+ <b>Examples</b>
+ </p>
+ <ul>
+ <li>
+ <code>ftps://myusername:mypassword@somehost/pub/downloads/somefile.tgz</code>
+ </li>
+ </ul>
+
+ </section>
+
+ <section name="SFTP">
+
+ <p>
+ Provides access to the files on an SFTP server (that is, an SSH
+ or SCP server).
+ </p>
+
+ <p>
+ <b>URI Format</b>
+ </p>
+
+ <p>
+ <code>sftp://[
+ <i>username</i>[:
+ <i>password</i>]@]
+ <i>hostname</i>[:
+ <i>port</i>][
+ <i>relative-path</i>]
+ </code>
+ </p>
+
+ <p>
+ <b>Examples</b>
+ </p>
+ <ul>
+ <li>
+ <code>sftp://myusername:mypassword@somehost/pub/downloads/somefile.tgz</code>
+ </li>
+ </ul>
+
+ <p>
+ By default, the path is relative to the user's home directory. This can be changed with:
+ </p>
+ <p>
+ <code>FtpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(options, false);</code>
+ </p>
+
+ </section>
+
+ <section name="CIFS">
+
+ <p>
+ The CIFS (sandbox) filesystem provides access to a CIFS server, such as
+ a Samba server, or a Windows share.
+ </p>
+ <p>
+ <b>URI Format</b>
+ </p>
+
+ <p>
+ <code>smb://[
+ <i>username</i>[:
+ <i>password</i>]@]
+ <i>hostname</i>[:
+ <i>port</i>][
+ <i>absolute-path</i>]
+ </code>
+ </p>
+
+ <p>
+ <b>Examples</b>
+ </p>
+
+ <ul>
+ <li>
+ <code>smb://somehost/home</code>
+ </li>
+ </ul>
+
+ </section>
+
+ <section name="Temporary Files">
+
+ <p>
+ Provides access to a temporary file system, or scratchpad,
+ that is deleted when Commons VFS shuts down. The temporary file
+ system is backed by a local file system.
+ </p>
+
+ <p>
+ <b>URI Format</b>
+ </p>
+
+ <p>
+ <code>tmp://[
+ <i>absolute-path</i>]
+ </code>
+ </p>
+
+ <p>
+ <b>Examples</b>
+ </p>
+
+ <ul>
+ <li>
+ <code>tmp://dir/somefile.txt</code>
+ </li>
+ </ul>
+ </section>
+
+ <section name="res">
+
+ <p>
+ This is not really a filesystem, it just tries to lookup a resource using javas <code>ClassLoader.getResource()</code>
+ and creates a VFS url for further processing.
+ </p>
+
+ <p>
+ <b>URI Format</b>
+ </p>
+
+ <p>
+ <code>res://[
+ <i>path</i>]
+ </code>
+ </p>
+
+ <p>
+ <b>Examples</b>
+ </p>
+
+ <ul>
+ <li>
+ <code>res:path/in/classpath/image.png</code><br/>
+ might result in
+ <code>jar:file://my/path/to/images.jar!/path/in/classpath/image.png</code><br/>
+ </li>
+ </ul>
+ </section>
+
+ <section name="ram">
+
+ <p>
+ A filesystem which stores all the data in memory (one byte array for each file content).
+ </p>
+
+ <p>
+ <b>URI Format</b>
+ </p>
+
+ <p>
+ <code>ram://[
+ <i>path</i>]
+ </code>
+ </p>
+
+ <p>
+ <b>File System Options</b>
+ <ul>
+ <li><b>maxsize</b> Maximum filesystem size (total bytes of all file contents).</li>
+ </ul>
+ </p>
+
+ <p>
+ <b>Examples</b>
+ </p>
+
+ <ul>
+ <li>
+ <code>ram:///any/path/to/file.txt</code>
+ </li>
+ </ul>
+ </section>
+
+ <section name="mime">
+
+ <p>
+ This (sandbox) filesystem can read mails and its attachements like archives.<br />
+ If a part in the parsed mail has no name, a dummy name will be generated.
+ The dummy name is: _body_part_X where X will be replaced by the part number.
+ </p>
+
+ <p>
+ <b>URI Format</b>
+ </p>
+
+ <p>
+ <code>mime://
+ <i>mime-file-uri</i>[!
+ <i>absolute-path</i>]
+ </code>
+ </p>
+
+ <p>
+ <b>Examples</b>
+ </p>
+
+ <ul>
+ <li>
+ <code>mime:file:///your/path/mail/anymail.mime!/</code>
+ </li>
+ <li>
+ <code>mime:file:///your/path/mail/anymail.mime!/filename.pdf</code>
+ </li>
+ <li>
+ <code>mime:file:///your/path/mail/anymail.mime!/_body_part_0</code>
+ </li>
+ </ul>
+ </section>
+
+ </body>
+</document>
diff --git a/trunk/src/site/xdoc/index.xml b/trunk/src/site/xdoc/index.xml
new file mode 100644
index 0000000..b77ccd6
--- /dev/null
+++ b/trunk/src/site/xdoc/index.xml
@@ -0,0 +1,99 @@
+<?xml version="1.0"?>
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+
+<document>
+ <properties>
+ <title>Commons Virtual File System</title>
+ <author email="dev@commons.apache.org">Apache Commons Developers</author>
+ </properties>
+
+ <body>
+ <section name="Commons Virtual File System">
+
+ <p>
+ Commons VFS provides a single API for accessing
+ various different file systems. It presents a uniform view of
+ the files from various different sources, such as the files on
+ local disk, on an HTTP server, or inside a Zip archive.
+ </p>
+
+ <p>Some of the features of Commons VFS are:</p>
+ <ul>
+ <li>
+ A single consistent API for accessing files of different
+ types.
+ </li>
+ <li>Support for numerous
+ <a href="filesystems.html">file system types</a>
+ .
+ </li>
+ <li>
+ Caching of file information. Caches information in-JVM,
+ and optionally can cache remote file information on the
+ local file system (replicator).
+ </li>
+ <li>Event delivery.</li>
+ <li>
+ Support for logical file systems made up of files from
+ various different file systems.
+ </li>
+ <li>
+ Utilities for integrating Commons VFS into applications,
+ such as a VFS-aware ClassLoader and URLStreamHandlerFactory.
+ </li>
+ <li>A set of VFS-enabled
+ <a href="anttasks.html">Ant tasks</a>
+ .
+ </li>
+ </ul>
+
+ </section>
+
+ <section name="Requirements">
+ <p>
+ Apache Commons VFS 2.1 requires Java 6. Many of the file systems require that optional components be present
+ in order for the protocol to be enabled. See the <a href="download.html">download and build</a> page for
+ information on the optional dependencies.
+ </p>
+ <p>
+ Apache Commons VFS 2.0 can be used in a Java 5 runtime.
+ </p>
+ </section>
+
+ <section name="News">
+ <p>
+ Apache Commons VFS 2.1 is a bugfix release to VFS 2.0. If you meet the requirements you should be able
+ to replace 2.0 with 2.1 without the need for changes to API consumers. VFS 2.1 has introduced some now
+ methods for provider interfaces (like <code>FileObject</code>). If you implement a VFS provider and use the
+ corresponding <code>Abstract*</code> or <code>Default*</code> classes, there should be no need to modify
+ the code or recompile the provider.
+ See the <a href="https://archive.apache.org/dist/commons/vfs/RELEASE_NOTES.txt">Release Notes</a> and the
+ <a href="commons-vfs2/clirr-report.html">Clirr Report</a> for details. VFS 2.1 adds a new read-only provider
+ for the Apache Hadoop (HDFS) File system.
+ </p><p>
+ Apache Commons VFS 2.0 adds support for FTPS and WebDav have been added in addition to many bugs
+ being fixed. Version 2.0 is not binary compatible with version 1.0. To insure that both 1.0 and 2.0 can
+ coexist version 2.0 has had its Maven groupId changed to org.apache.commons, its Maven artifact changed
+ to commons-vfs2, and the package names are now org.apache.commons.vfs2. The API changes are fairly minor
+ and will mostly impact provider implementations.
+ </p>
+ </section>
+
+ </body>
+</document>
+
diff --git a/trunk/src/site/xdoc/issue-tracking.xml b/trunk/src/site/xdoc/issue-tracking.xml
new file mode 100644
index 0000000..93c6fbe
--- /dev/null
+++ b/trunk/src/site/xdoc/issue-tracking.xml
@@ -0,0 +1,102 @@
+<?xml version="1.0"?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements. See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to You under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+-->
+<!--
+ +======================================================================+
+ |**** ****|
+ |**** THIS FILE IS GENERATED BY THE COMMONS BUILD PLUGIN ****|
+ |**** DO NOT EDIT DIRECTLY ****|
+ |**** ****|
+ +======================================================================+
+ | TEMPLATE FILE: issue-tracking-template.xml |
+ | commons-build-plugin/trunk/src/main/resources/commons-xdoc-templates |
+ +======================================================================+
+ | |
+ | 1) Re-generate using: mvn commons:jira-page |
+ | |
+ | 2) Set the following properties in the component's pom: |
+ | - commons.jira.id (required, alphabetic, upper case) |
+ | - commons.jira.pid (required, numeric) |
+ | |
+ | 3) Example Properties |
+ | |
+ | <properties> |
+ | <commons.jira.id>MATH</commons.jira.id> |
+ | <commons.jira.pid>12310485</commons.jira.pid> |
+ | </properties> |
+ | |
+ +======================================================================+
+-->
+<document>
+ <properties>
+ <title>Apache Commons VFS Issue tracking</title>
+ <author email="dev@commons.apache.org">Commons Documentation Team</author>
+ </properties>
+ <body>
+
+ <section name="Apache Commons VFS Issue tracking">
+ <p>
+ Apache Commons VFS uses <a href="http://issues.apache.org/jira/">ASF JIRA</a> for tracking issues.
+ See the <a href="http://issues.apache.org/jira/browse/VFS">Apache Commons VFS JIRA project page</a>.
+ </p>
+
+ <p>
+ To use JIRA you may need to <a href="http://issues.apache.org/jira/secure/Signup!default.jspa">create an account</a>
+ (if you have previously created/updated Commons issues using Bugzilla an account will have been automatically
+ created and you can use the <a href="http://issues.apache.org/jira/secure/ForgotPassword!default.jspa">Forgot Password</a>
+ page to get a new password).
+ </p>
+
+ <p>
+ If you would like to report a bug, or raise an enhancement request with
+ Apache Commons VFS please do the following:
+ <ol>
+ <li><a href="http://issues.apache.org/jira/secure/IssueNavigator.jspa?reset=true&pid=12310495&sorter/field=issuekey&sorter/order=DESC&status=1&status=3&status=4">Search existing open bugs</a>.
+ If you find your issue listed then please add a comment with your details.</li>
+ <li><a href="mail-lists.html">Search the mailing list archive(s)</a>.
+ You may find your issue or idea has already been discussed.</li>
+ <li>Decide if your issue is a bug or an enhancement.</li>
+ <li>Submit either a <a href="http://issues.apache.org/jira/secure/CreateIssueDetails!init.jspa?pid=12310495&issuetype=1&priority=4&assignee=-1">bug report</a>
+ or <a href="http://issues.apache.org/jira/secure/CreateIssueDetails!init.jspa?pid=12310495&issuetype=4&priority=4&assignee=-1">enhancement request</a>.</li>
+ </ol>
+ </p>
+
+ <p>
+ Please also remember these points:
+ <ul>
+ <li>the more information you provide, the better we can help you</li>
+ <li>test cases are vital, particularly for any proposed enhancements</li>
+ <li>the developers of Apache Commons VFS are all unpaid volunteers</li>
+ </ul>
+ </p>
+
+ <p>
+ For more information on subversion and creating patches see the
+ <a href="http://www.apache.org/dev/contributors.html">Apache Contributors Guide</a>.
+ </p>
+
+ <p>
+ You may also find these links useful:
+ <ul>
+ <li><a href="http://issues.apache.org/jira/secure/IssueNavigator.jspa?reset=true&pid=12310495&sorter/field=issuekey&sorter/order=DESC&status=1&status=3&status=4">All Open Apache Commons VFS bugs</a></li>
+ <li><a href="http://issues.apache.org/jira/secure/IssueNavigator.jspa?reset=true&pid=12310495&sorter/field=issuekey&sorter/order=DESC&status=5&status=6">All Resolved Apache Commons VFS bugs</a></li>
+ <li><a href="http://issues.apache.org/jira/secure/IssueNavigator.jspa?reset=true&pid=12310495&sorter/field=issuekey&sorter/order=DESC">All Apache Commons VFS bugs</a></li>
+ </ul>
+ </p>
+ </section>
+ </body>
+</document>
diff --git a/trunk/src/site/xdoc/mail-lists.xml b/trunk/src/site/xdoc/mail-lists.xml
new file mode 100644
index 0000000..4f3ef47
--- /dev/null
+++ b/trunk/src/site/xdoc/mail-lists.xml
@@ -0,0 +1,205 @@
+<?xml version="1.0"?>
+<!--
+Licensed to the Apache Software Foundation (ASF) under one or more
+contributor license agreements. See the NOTICE file distributed with
+this work for additional information regarding copyright ownership.
+The ASF licenses this file to You under the Apache License, Version 2.0
+(the "License"); you may not use this file except in compliance with
+the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+-->
+<!--
+ +======================================================================+
+ |**** ****|
+ |**** THIS FILE IS GENERATED BY THE COMMONS BUILD PLUGIN ****|
+ |**** DO NOT EDIT DIRECTLY ****|
+ |**** ****|
+ +======================================================================+
+ | TEMPLATE FILE: mail-lists-template.xml |
+ | commons-build-plugin/trunk/src/main/resources/commons-xdoc-templates |
+ +======================================================================+
+ | |
+ | 1) Re-generate using: mvn commons:mail-page |
+ | |
+ | 2) Set the following properties in the component's pom: |
+ | - commons.componentid (required, alphabetic, lower case) |
+ | |
+ | 3) Example Properties |
+ | |
+ | <properties> |
+ | <commons.componentid>math</commons.componentid> |
+ | </properties> |
+ | |
+ +======================================================================+
+-->
+<document>
+ <properties>
+ <title>Apache Commons VFS Mailing Lists</title>
+ <author email="dev@commons.apache.org">Apache Commons Documentation Team</author>
+ </properties>
+ <body>
+
+ <section name="Overview">
+ <p>
+ <a href="index.html">Apache Commons VFS</a> shares mailing lists with all the other
+ <a href="http://commons.apache.org/components.html">Commons Components</a>.
+ To make it easier for people to only read messages related to components they are interested in,
+ the convention in Commons is to prefix the subject line of messages with the component's name,
+ for example:
+ <ul>
+ <li>[vfs] Problem with the ...</li>
+ </ul>
+ </p>
+ <p>
+ Questions related to the usage of Apache Commons VFS should be posted to the
+ <a href="http://mail-archives.apache.org/mod_mbox/commons-user/">User List</a>.
+ <br />
+ The <a href="http://mail-archives.apache.org/mod_mbox/commons-dev/">Developer List</a>
+ is for questions and discussion related to the development of Apache Commons VFS.
+ <br />
+ Please do not cross-post; developers are also subscribed to the user list.
+ <br />
+ You must be subscribed to post to the mailing lists. Follow the Subscribe links below
+ to subscribe.
+ </p>
+ <p>
+ <strong>Note:</strong> please don't send patches or attachments to any of the mailing lists.
+ Patches are best handled via the <a href="issue-tracking.html">Issue Tracking</a> system.
+ Otherwise, please upload the file to a public server and include the URL in the mail.
+ </p>
+ </section>
+
+ <section name="Apache Commons VFS Mailing Lists">
+ <p>
+ <strong>Please prefix the subject line of any messages for <a href="index.html">Apache Commons VFS</a>
+ with <i>[vfs]</i></strong> - <i>thanks!</i>
+ <br />
+ <br />
+ </p>
+
+ <table>
+ <tr>
+ <th>Name</th>
+ <th>Subscribe</th>
+ <th>Unsubscribe</th>
+ <th>Post</th>
+ <th>Archive</th>
+ <th>Other Archives</th>
+ </tr>
+
+
+ <tr>
+ <td>
+ <strong>Commons User List</strong>
+ <br /><br />
+ Questions on using Apache Commons VFS.
+ <br /><br />
+ </td>
+ <td><a href="mailto:user-subscribe@commons.apache.org">Subscribe</a></td>
+ <td><a href="mailto:user-unsubscribe@commons.apache.org">Unsubscribe</a></td>
+ <td><a href="mailto:user@commons.apache.org?subject=[vfs]">Post</a></td>
+ <td><a href="http://mail-archives.apache.org/mod_mbox/commons-user/">mail-archives.apache.org</a></td>
+ <td><a href="http://markmail.org/list/org.apache.commons.users/">markmail.org</a><br />
+ <a href="http://www.mail-archive.com/user@commons.apache.org/">www.mail-archive.com</a><br />
+ <a href="http://news.gmane.org/gmane.comp.jakarta.commons.devel">news.gmane.org</a>
+ </td>
+ </tr>
+
+
+ <tr>
+ <td>
+ <strong>Commons Developer List</strong>
+ <br /><br />
+ Discussion of development of Apache Commons VFS.
+ <br /><br />
+ </td>
+ <td><a href="mailto:dev-subscribe@commons.apache.org">Subscribe</a></td>
+ <td><a href="mailto:dev-unsubscribe@commons.apache.org">Unsubscribe</a></td>
+ <td><a href="mailto:dev@commons.apache.org?subject=[vfs]">Post</a></td>
+ <td><a href="http://mail-archives.apache.org/mod_mbox/commons-dev/">mail-archives.apache.org</a></td>
+ <td><a href="http://markmail.org/list/org.apache.commons.dev/">markmail.org</a><br />
+ <a href="http://www.mail-archive.com/dev@commons.apache.org/">www.mail-archive.com</a><br />
+ <a href="http://news.gmane.org/gmane.comp.jakarta.commons.devel">news.gmane.org</a>
+ </td>
+ </tr>
+
+
+ <tr>
+ <td>
+ <strong>Commons Issues List</strong>
+ <br /><br />
+ Only for e-mails automatically generated by the <a href="issue-tracking.html">issue tracking</a> system.
+ <br /><br />
+ </td>
+ <td><a href="mailto:issues-subscribe@commons.apache.org">Subscribe</a></td>
+ <td><a href="mailto:issues-unsubscribe@commons.apache.org">Unsubscribe</a></td>
+ <td><i>read only</i></td>
+ <td><a href="http://mail-archives.apache.org/mod_mbox/commons-issues/">mail-archives.apache.org</a></td>
+ <td><a href="http://markmail.org/list/org.apache.commons.issues/">markmail.org</a><br />
+ <a href="http://www.mail-archive.com/issues@commons.apache.org/">www.mail-archive.com</a>
+ </td>
+ </tr>
+
+
+ <tr>
+ <td>
+ <strong>Commons Commits List</strong>
+ <br /><br />
+ Only for e-mails automatically generated by the <a href="source-repository.html">source control</a> sytem.
+ <br /><br />
+ </td>
+ <td><a href="mailto:commits-subscribe@commons.apache.org">Subscribe</a></td>
+ <td><a href="mailto:commits-unsubscribe@commons.apache.org">Unsubscribe</a></td>
+ <td><i>read only</i></td>
+ <td><a href="http://mail-archives.apache.org/mod_mbox/commons-commits/">mail-archives.apache.org</a></td>
+ <td><a href="http://markmail.org/list/org.apache.commons.commits/">markmail.org</a><br />
+ <a href="http://www.mail-archive.com/commits@commons.apache.org/">www.mail-archive.com</a>
+ </td>
+ </tr>
+
+ </table>
+
+ </section>
+ <section name="Apache Mailing Lists">
+ <p>
+ Other mailing lists which you may find useful include:
+ </p>
+
+ <table>
+ <tr>
+ <th>Name</th>
+ <th>Subscribe</th>
+ <th>Unsubscribe</th>
+ <th>Post</th>
+ <th>Archive</th>
+ <th>Other Archives</th>
+ </tr>
+ <tr>
+ <td>
+ <strong>Apache Announce List</strong>
+ <br /><br />
+ General announcements of Apache project releases.
+ <br /><br />
+ </td>
+ <td><a class="externalLink" href="mailto:announce-subscribe@apache.org">Subscribe</a></td>
+ <td><a class="externalLink" href="mailto:announce-unsubscribe@apache.org">Unsubscribe</a></td>
+ <td><i>read only</i></td>
+ <td><a class="externalLink" href="http://mail-archives.apache.org/mod_mbox/www-announce/">mail-archives.apache.org</a></td>
+ <td><a class="externalLink" href="http://markmail.org/list/org.apache.announce/">markmail.org</a><br />
+ <a class="externalLink" href="http://old.nabble.com/Apache-News-and-Announce-f109.html">old.nabble.com</a><br />
+ <a class="externalLink" href="http://www.mail-archive.com/announce@apache.org/">www.mail-archive.com</a><br />
+ <a class="externalLink" href="http://news.gmane.org/gmane.comp.apache.announce">news.gmane.org</a>
+ </td>
+ </tr>
+ </table>
+
+ </section>
+ </body>
+</document>
diff --git a/trunk/src/site/xdoc/testing.xml b/trunk/src/site/xdoc/testing.xml
new file mode 100644
index 0000000..3903a5d
--- /dev/null
+++ b/trunk/src/site/xdoc/testing.xml
@@ -0,0 +1,172 @@
+<!--
+ Licensed to the Apache Software Foundation (ASF) under one or more
+ contributor license agreements. See the NOTICE file distributed with
+ this work for additional information regarding copyright ownership.
+ The ASF licenses this file to You under the Apache License, Version 2.0
+ (the "License"); you may not use this file except in compliance with
+ the License. You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
+-->
+<document>
+ <properties>
+ <title>Testing</title>
+ <author email="dev@commons.apache.org">Apache Commons Developers</author>
+ </properties>
+
+ <body>
+ <section name="VFS Test Suite">
+ <p>
+ Apache Commons VFS comes with a suite of (nearly 2000) tests (in <code>core/src/test</code>). The JUnit framework
+ is used, and executed at build time via the Maven
+ <a href="http://maven.apache.org/surefire/maven-surefire-plugin/">Surefire plugin</a> by the <code>mvn test</code> goal.
+ It you plan to contribute a patch for a bug or feature, make sure to also provide a test
+ which can reproduce the bug or exercise the new feature. Also run the whole test suite against the patched code.
+ </p>
+ <p>
+ The <a href="http://junit.org">JUnit</a> tests will execute unit, compile but also integration tests to test the API and the implementation.
+ The local file provider is tested in a directory of the local file system. Virtual providers (compression and archive)
+ and resource access is based on this test directory as well. For testing the other providers some test servers are started.
+ The following table described the details (for versions have a look in the
+ <a href="commons-vfs2/dependencies.html#test">dependency report</a>):
+ </p>
+<table><tr><th>Provider</th><th>Tested Against</th><th>External</th></tr>
+<tr><td>ftp</td><td><a href="http://mina.apache.org/ftpserver-project/">Apache FtpServer</a></td><td>-Pftp -Dtest.ftp.uri=ftp://test:test@localhost:123</td></tr>
+<tr><td>ftps</td><td><a href="http://mina.apache.org/ftpserver-project/">Apache FtpServer</a></td><td>-Pftps -Dtest.ftps.uri=ftps://test:test@localhost:123</td></tr>
+<tr><td>hdfs</td><td>Apache Hadoop HDFS (<a href="https://wiki.apache.org/hadoop/HowToDevelopUnitTests">MiniDFSCluster</a>)</td><td>-P!no-test-hdfs (see below)</td></tr>
+<tr><td>http</td><td>NHttpServer (local adaption of org.apache.http.examples.nio.NHttpServer)</td><td>-Phttp -Dtest.http.uri=http://localhost:123</td></tr>
+<tr><td>https</td><td>(not tested)</td><td>N/A</td></tr>
+<tr><td>jar</td><td>Local File Provider</td><td>N/A</td></tr>
+<tr><td>local</td><td>Local File system</td><td>N/A</td></tr>
+<tr><td>ram</td><td>In Memory test</td><td>N/A</td></tr>
+<tr><td>res</td><td>Local File Provider / JAR Provider</td><td>N/A</td></tr>
+<tr><td>sftp</td><td><a href="http://mina.apache.org/sshd-project/index.html">Apache SSHD</a></td><td>-Psftp -Dtest.sftp.uri=sftp://testtest@localhost:123</td></tr>
+<tr><td>tmp</td><td>Local File system</td><td>N/A</td></tr>
+<tr><td>url</td><td>NHttpServer (local adaption of org.apache.http.examples.nio.NHttpServer)<br/>Local File system</td><td>-Phttp -Dtest.http.uri=http://localhost:128</td></tr>
+<tr><td>webdav</td><td><a href="http://jackrabbit.apache.org/standalone-server.html">Apache Jackrabbit Standalone Server</a></td><td>-Pwebdav -Dtest.webdav.uri=webdav://admin@localhost:123/repository/default</td></tr>
+<!-- <tr><td>webdavs</td><td>Apache Jackrabbit Standalone</td><td>-Pwebdav -Dtest.webdav.uri=webdav://admin@localhost:123/repository/default</td></tr> -->
+<tr><td>zip</td><td>Local File Provider</td><td>N/A</td></tr>
+<tr><td>smb (sandbox)</td><td>(not tested)</td><td>-Psmb -Dtest.smb.uri=smb://DOMAIN\User:Pass@host/C$/commons-vfs2/core/target/test-classes/test-data</td></tr>
+</table>
+ <p>
+ Some tests are operating-system specific. Some Windows File Name tests are only run on Windows
+ and the HDFS test is skipped in case of Windows (because it requires additional binaries). It is therefore
+ a good idea to run the tests at least on Windows and Linux/Unix before release. The <code>smb</code> provider
+ from the sandbox is not tested unless you specify a <code>-Dtest.smb.uri</code> and the <code>-Psmb</code> profile.
+ </p>
+ </section>
+ <section name="Running HDFS tests on Windows">
+ <p>
+ The HDFS integration tests use the HDFS MiniCluster. This does not work on Windows without special preparation:
+ you need to build and provide the (2.6.0) native binary (<code>winutils.exe</code>) and library (<code>hadoop.dll</code>) for the
+ MiniCluster used in the test cases. Both files are not part of the Hadoop Commons 2.6.0
+ distribution (<a href="https://issues.apache.org/jira/browse/HADOOP-10051">HADOOP-10051</a>). After you built
+ a compatible version, put them on your Windows <code>PATH</code> and then run the tests
+ by disabling the <code>no-test-hdfs</code> profile, or by requesting explicitly the excluded tests:
+ </p>
+ <source><![CDATA[
+> set VFS=C:\commons-vfs2-project\core
+> cd %VFS%\core
+> mkdir bin\
+> copy \temp\winutils.exe \temp\hadoop.dll bin\
+> set HADOOP_HOME=%VFS%\core
+> set PATH=%VFS%\core\bin;%PATH%
+> winutils.exe systeminfo
+8518668288,8520572928,4102033408,4544245760,8,1600000,6042074
+> mvn -P!no-test-hdfs clean test # runs all test and HDFS tests
+> mvn clean test -Dtest=org.apache.commons.vfs2.provider.hdfs.test.HdfsFileProviderTest,org.apache.commons.vfs2.provider.hdfs.test.HdfsFileProviderTestCase
+...
+Tests run: 13, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 13.006 sec - in org.apache.commons.vfs2.provider.hdfs.test.HdfsFileProviderTest
+Tests run: 77, Failures: 0, Errors: 0, Skipped: 0, Time elapsed: 11.728 sec - in org.apache.commons.vfs2.provider.hdfs.test.HdfsFileProviderTestCase]]></source>
+ </section>
+
+ <section name="Running SMB tests against Windows">
+ <p>
+ The SMB provider from the sandbox project cannot be tested automatically. You need to prepare a CIFS/SMB server
+ to test it manually. If you develop on Windows, the following procedure uses the Windows File Sharing and does
+ not require to prepare the data directory (as you can directly point to your workspace):
+ </p>
+ <source><![CDATA[
+> set VFS=C:\commons-vfs2-project
+> cd %VFS%
+> mvn clean install -Pinclude-sandbox -DskipTests # prepares test data and parent
+> cd %VFS%\sandbox
+> mvn test -Psmb -Dtest.smb.url=smb//Domain\User:Pass@yourhost/C$/commons-vfs2-project/core/target/test-classes/test-data
+...
+Tests run: 82, Failures: 0, Errors: 1, Skipped: 0]]></source>
+ <p>
+ Note: there is a known test failure in this case, see
+ <a href="https://issues.apache.org/jira/browse/VFS-562">VFS-562</a> on the JIRA bug tracker if you want
+ to help.
+ </p>
+ </section>
+
+ <section name="Running tests with external servers">
+ <p>
+ In order to test VFS for compatibility with other implementations (or in case of SMB to
+ test it manually) some of the integration tests can be configured to connect to custom URL.
+ This generally involves preparing the server, selecting a profile and specifying the URL in
+ a system property (see table above).
+ </p>
+
+ <subsection name="Preparing external Servers">
+ <p>
+ If you want to run the tests against external servers, run <code>mvn install</code>.
+ This will compile all the source and test source and then run all the tests
+ for providers that use the local file system.
+ After running the maven build, the test data can be found in
+ <code>core/target/test-classes/test-data/</code>.
+ </p>
+ <p>
+ Each repository/server should contain the following list of files for the tests to
+ complete successfully.
+ </p>
+ <source><![CDATA[
+code/sealed/AnotherClass.class
+code/ClassToLoad.class
+largefile.tar.gz
+nested.jar
+nested.tar
+nested.tbz2
+nested.tgz
+nested.zip
+read-tests/dir1/file1.txt
+read-tests/dir1/file2.txt
+read-tests/dir1/file3.txt
+read-tests/dir1/subdir1/file1.txt
+read-tests/dir1/subdir1/file2.txt
+read-tests/dir1/subdir1/file3.txt
+read-tests/dir1/subdir2/file1.txt
+read-tests/dir1/subdir2/file2.txt
+read-tests/dir1/subdir2/file3.txt
+read-tests/dir1/subdir3/file1.txt
+read-tests/dir1/subdir3/file2.txt
+read-tests/dir1/subdir3/file3.txt
+read-tests/empty.txt
+read-tests/file1.txt
+read-tests/file space.txt
+read-tests/file%.txt
+test-hash-#test.txt
+test.jar
+test.mf
+test.policy
+test.tar
+test.tbz2
+test.tgz
+test.zip
+write-tests/]]></source>
+ <p>
+ The Apache Commons Wiki contains a list of configuration examples for external servers.
+ Please consider contributing if you have set up a specific scenario:
+ <a href="https://wiki.apache.org/commons/VfsTestServers">https://wiki.apache.org/commons/VfsTestServers</a>.
+ </p>
+ </subsection>
+ </section>
+ </body>
+</document>