Installing a File System for SFTP

Lee Painter

In order for SFTP to function you need to install a File System. We provide a couple of implementations out of the box. Again its just a case of calling the methods in your configure method to initialise the file system.

Direct File System


This exposes the direct file system of your host operating system over SFTP. 

sshContext.setFileSystemProvider(new DirectFileSytemFactory());


This will use standard home directory locations, for example /home/${username} on Linux, /Users/${username} on OSX and C:\Documents and Settings\${username} on Windows. This is unlikely to be suitable for a production environment so we recommend implementing your own DirectFileHomeFactory and passing this into the DirectFileSystemFactory on creation.


Virtual File System


The Virtual File System is a much more flexible implementation which allows you to mount different types of file systems together into a single file system.

The following code will initialize the virtual file system with a single home mount using a native path under the servers working directory. 

sshContext.setFileSystemProvider(new FileSystemFactory() {
@Override
public FileSystem createInstance(Connection con, String protocolInUse)
throws PermissionDeniedException, IOException {
return new AbstractFileSystem(
new VirtualFileFactory(
new VirtualMountTemplate("/", "conf/${username}", new VFSFileFactory())),
con, protocolInUse);
}
});

 

Further mounts can be added simply by adding further VirtualMountTemplate definitions to the VirtualFileFactory constructor. Only one mount is required and that is the users home directory.

VFSFileFactory as used here is an implementation that uses commons VFS file system, so any valid URL can be used to create a mount for example "ftp://example.com/path"

 

Creating Your Own


Creating your own file system is simply a matter of implementing AbstractFile and providing a AbstractFileFactory to match. Implementing AbstractFile is very similer to the standard java.io.File interface. Our complete implementation of DirectFile is available at the bottom of this article for you to download. This should serve as a reference implementation for your own file system. Remember, the AbstractFile represents a single file system object in your file system i.e. a file, or a directory and on this object you can perform all the operations that are possible on a file system object.

The AbstractFileFactory implementation creates these given a path, therefore when you receive a path of "/" you would return an AbstractFile object that represents the root of the file system and thus calling that objects getChildren method would return all the file objects that sit immediately under the root e.g. "/file1", "/file2", "/directory1" etc.