org.apache.commons.vfs2.FileSystemManager Java Examples

The following examples show how to use org.apache.commons.vfs2.FileSystemManager. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DefaultFileSystemManagerProvider.java    From spoofax with Apache License 2.0 6 votes vote down vote up
@Override public FileSystemManager get() {
    try {
        final DefaultFileSystemManager manager = new DefaultFileSystemManager();

        manager.setFilesCache(new DefaultFilesCache());
        manager.setCacheStrategy(CacheStrategy.ON_RESOLVE);

        final String baseTmpDir = System.getProperty("java.io.tmpdir");
        final File tempDir = new File(baseTmpDir, "vfs_cache" + new Random().nextLong()).getAbsoluteFile();
        final DefaultFileReplicator replicator = new DefaultFileReplicator(tempDir);
        manager.setTemporaryFileStore(replicator);
        manager.setReplicator(replicator);

        addDefaultProvider(manager);
        addProviders(manager);
        setBaseFile(manager);

        manager.init();

        return manager;
    } catch(FileSystemException e) {
        throw new RuntimeException("Cannot initialize resource service: " + e.getMessage(), e);
    }
}
 
Example #2
Source File: VFSFileSystem.java    From commons-configuration with Apache License 2.0 6 votes vote down vote up
@Override
public String getBasePath(final String path)
{
    if (UriParser.extractScheme(path) == null)
    {
        return super.getBasePath(path);
    }
    try
    {
        final FileSystemManager fsManager = VFS.getManager();
        final FileName name = fsManager.resolveURI(path);
        return name.getParent().getURI();
    }
    catch (final FileSystemException fse)
    {
        fse.printStackTrace();
        return null;
    }
}
 
Example #3
Source File: StorageObject.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
/** 删除内容,同时判断上一级目录(只判断一级)是否为空,为空则删除上一级目录 */
public void deleteContent(StorageMapping mapping) throws Exception {
	FileSystemManager manager = this.getFileSystemManager();
	String prefix = this.getPrefix(mapping);
	String path = this.path();
	FileSystemOptions options = this.getOptions(mapping);
	try (FileObject fo = manager.resolveFile(prefix + PATHSEPARATOR + path, options)) {
		if (fo.exists() && fo.isFile()) {
			fo.delete();
			if ((!StringUtils.startsWith(path, PATHSEPARATOR)) && (StringUtils.contains(path, PATHSEPARATOR))) {
				FileObject parent = fo.getParent();
				if ((null != parent) && parent.exists() && parent.isFolder()) {
					if (parent.getChildren().length == 0) {
						parent.delete();
					}
				}
			}
		}
		manager.closeFileSystem(fo.getFileSystem());
	}
}
 
Example #4
Source File: Http4FilesCacheTestCase.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Tests https://issues.apache.org/jira/browse/VFS-426
 */
@Test
public void testQueryStringUrls() throws FileSystemException {
    final String noQueryStringUrl = "http4://commons.apache.org/vfs";
    final String queryStringUrl = "http4://commons.apache.org/vfs?query=string";
    final String queryStringUrl2 = "http4://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
}
 
Example #5
Source File: PublishUtil.java    From pentaho-reporting with GNU Lesser General Public License v2.1 6 votes vote down vote up
public static FileObject createVFSConnection( final FileSystemManager fileSystemManager,
    final AuthenticationData loginData ) throws FileSystemException {
  if ( fileSystemManager == null ) {
    throw new NullPointerException();
  }
  if ( loginData == null ) {
    throw new NullPointerException();
  }

  final String versionText = loginData.getOption( SERVER_VERSION );
  final int version = ParserUtil.parseInt( versionText, SERVER_VERSION_SUGAR );

  final String normalizedUrl = normalizeURL( loginData.getUrl(), version );
  final FileSystemOptions fileSystemOptions = new FileSystemOptions();
  final PentahoSolutionsFileSystemConfigBuilder configBuilder = new PentahoSolutionsFileSystemConfigBuilder();
  configBuilder.setTimeOut( fileSystemOptions, getTimeout( loginData ) * 1000 );
  configBuilder.setUserAuthenticator( fileSystemOptions, new StaticUserAuthenticator( normalizedUrl, loginData
      .getUsername(), loginData.getPassword() ) );
  return fileSystemManager.resolveFile( normalizedUrl, fileSystemOptions );
}
 
Example #6
Source File: ZipFileObjectTestCase.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Tests that we can get a stream from one file in a zip file, then close another file from the same zip, then
 * process the initial input stream.
 *
 * @throws IOException
 */
@Test
public void testReadingOneAfterClosingAnotherFile() throws IOException {
    final File newZipFile = createTempFile();
    final FileSystemManager manager = VFS.getManager();
    final FileObject zipFileObject1;
    final InputStream inputStream1;
    try (final FileObject zipFileObject = manager.resolveFile("zip:file:" + newZipFile.getAbsolutePath())) {
        // leave resources open
        zipFileObject1 = zipFileObject.resolveFile(NESTED_FILE_1);
        inputStream1 = zipFileObject1.getContent().getInputStream();
    }
    // The zip file is "closed", but we read from the stream now.
    readAndAssert(zipFileObject1, inputStream1, "1");
    // clean up
    zipFileObject1.close();
    assertDelete(newZipFile);
}
 
Example #7
Source File: DefaultFileContentTest.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
@Test
public void testMarkingWorks() throws Exception {
    final File temp = File.createTempFile("temp-file-name", ".tmp");
    final FileSystemManager fileSystemManager = VFS.getManager();

    try (FileObject file = fileSystemManager.resolveFile(temp.getAbsolutePath())) {
        try (OutputStream outputStream = file.getContent().getOutputStream()) {
            outputStream.write(expected.getBytes());
            outputStream.flush();
        }
        try (InputStream stream = file.getContent().getInputStream()) {
            if (stream.markSupported()) {
                for (int i = 0; i < 10; i++) {
                    stream.mark(0);
                    final byte[] data = new byte[100];
                    stream.read(data, 0, 7);
                    stream.read();
                    Assert.assertEquals(expected, new String(data).trim());
                    stream.reset();
                }
            }
        }
    }
}
 
Example #8
Source File: FileSystemManagerFactoryTestCase.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #9
Source File: BakeWatcher.java    From jbake with MIT License 6 votes vote down vote up
/**
 * Starts watching the file system for changes to trigger a bake.
 *
 * @param config JBakeConfiguration settings
 */
public void start(JBakeConfiguration config) {
    try {
        FileSystemManager fsMan = VFS.getManager();
        FileObject listenPath = fsMan.resolveFile(config.getContentFolder().toURI());
        FileObject templateListenPath = fsMan.resolveFile(config.getTemplateFolder().toURI());
        FileObject assetPath = fsMan.resolveFile(config.getAssetFolder().toURI());

        logger.info("Watching for (content, template, asset) changes in [{}]", config.getSourceFolder().getPath());
        DefaultFileMonitor monitor = new DefaultFileMonitor(new CustomFSChangeListener(config));
        monitor.setRecursive(true);
        monitor.addFile(listenPath);
        monitor.addFile(templateListenPath);
        monitor.addFile(assetPath);
        monitor.start();
    } catch (FileSystemException e) {
        logger.error("Problems watching filesystem changes", e);
    }
}
 
Example #10
Source File: ZipProviderWithCharsetNullTestCase.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the base folder for read tests.
 */
@Override
public FileObject getBaseTestFolder(final FileSystemManager manager) throws Exception {
    final FileSystemOptions opts = new FileSystemOptions();
    final ZipFileSystemConfigBuilder builder = ZipFileSystemConfigBuilder.getInstance();
    // Tests null as the default.
    builder.setCharset(opts, null);

    final File zipFile = AbstractVfsTestCase.getTestResource("test.zip");
    final String uri = "zip:file:" + zipFile.getAbsolutePath() + "!/";
    final FileObject resolvedFile = manager.resolveFile(uri, opts);
    final FileSystem fileSystem = resolvedFile.getFileSystem();
    Assert.assertTrue(fileSystem instanceof ZipFileSystem);
    final ZipFileSystem zipFileSystem = (ZipFileSystem) fileSystem;
    Assert.assertNull(zipFileSystem.getCharset());
    return resolvedFile;
}
 
Example #11
Source File: UrlTests.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Tests FindFiles with a file name 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");
    }
}
 
Example #12
Source File: AbstractSftpProviderTestCase.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
    final FileObject fileObject = manager.resolveFile(uri, fileSystemOptions);
    this.fileSystem = (SftpFileSystem) fileObject.getFileSystem();
    return fileObject;
}
 
Example #13
Source File: FileNamePerformance.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
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:[email protected]/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:[email protected]/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");
}
 
Example #14
Source File: RamProviderTestCase.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example #15
Source File: VFSClassLoader.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * 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 (!FileObjectUtils.exists(file)) {
            // 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);
    }
}
 
Example #16
Source File: NestedZipTestCase.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * 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("/");
}
 
Example #17
Source File: ZipProviderTestCase.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #18
Source File: NestedTbz2TestCase.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * 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("/");
}
 
Example #19
Source File: ParseXmlInZipTestCase.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
private void testResolveAndParseXmlInZip(final String xmlPathInZip, final String xsdPathInZip)
        throws IOException, FileSystemException, SAXException {
    final File newZipFile = createTempFile();
    final String zipFilePath = "zip:file:" + newZipFile.getAbsolutePath();
    final FileSystemManager manager = VFS.getManager();
    try (final FileObject zipFileObject = manager.resolveFile(zipFilePath)) {
        try (final FileObject xmlFileObject = zipFileObject.resolveFile(xmlPathInZip)) {
            try (final InputStream inputStream = xmlFileObject.getContent().getInputStream()) {
                final Document document = newDocumentBuilder(zipFileObject, xmlFileObject, xsdPathInZip)
                        .parse(inputStream);
                Assert.assertNotNull(document);
            }
        }
    }
}
 
Example #20
Source File: ParseXmlInZipTestCase.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
@Test
public void testParseXmlInZip() throws IOException, SAXException {
    final File newZipFile = createTempFile();
    final String xmlFilePath = "zip:file:" + newZipFile.getAbsolutePath() + "!/read-xml-tests/file1.xml";
    final FileSystemManager manager = VFS.getManager();
    try (final FileObject zipFileObject = manager.resolveFile(xmlFilePath)) {
        try (final InputStream inputStream = zipFileObject.getContent().getInputStream()) {
            final Document document = newDocumentBuilder(zipFileObject, zipFileObject, null).parse(inputStream);
            Assert.assertNotNull(document);
        }
    }
}
 
Example #21
Source File: ZipFileObjectTestCase.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Tests that we can resolve a file in a Zip file, then close the container zip, which should still let us delete
 * the Zip file.
 *
 * @throws IOException
 */
@Test
public void testResolveNestedFileWithoutCleanup() throws IOException {
    final File newZipFile = createTempFile();
    final FileSystemManager manager = VFS.getManager();
    try (final FileObject zipFileObject = manager.resolveFile("zip:file:" + newZipFile.getAbsolutePath())) {
        @SuppressWarnings({ "unused", "resource" })
        // We resolve a nested file and do nothing else.
        final FileObject zipFileObject1 = zipFileObject.resolveFile(NESTED_FILE_1);
    }
    assertDelete(newZipFile);
}
 
Example #22
Source File: DirectoryFileFilterExample.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {

        // Example, how to print out a list of the current directory's
        // subdirectories
        final FileSystemManager fsManager = VFS.getManager();
        final FileObject dir = fsManager.toFileObject(new File("."));
        final FileObject[] files = dir.findFiles(new FileFilterSelector(DirectoryFileFilter.DIRECTORY));
        for (FileObject file : files) {
            System.out.println(file);
        }
    }
 
Example #23
Source File: NestedJarTestCase.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * 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("/");
}
 
Example #24
Source File: SuffixFileFilterExample.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {

        // Example, to retrieve and print all *.java files in the current
        // directory
        final FileSystemManager fsManager = VFS.getManager();
        final FileObject dir = fsManager.toFileObject(new File("."));
        final FileObject[] files = dir.findFiles(new FileFilterSelector(new SuffixFileFilter(".java")));
        for (FileObject file : files) {
            System.out.println(file);
        }

    }
 
Example #25
Source File: FileFileFilterExample.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {

        // Example, how to print out a list of the real files within the current
        // directory
        final FileSystemManager fsManager = VFS.getManager();
        final FileObject dir = fsManager.toFileObject(new File("."));
        final FileObject[] files = dir.findFiles(new FileFilterSelector(FileFileFilter.FILE));
        for (FileObject file : files) {
            System.out.println(file);
        }
    }
 
Example #26
Source File: AgeFileFilterExample.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
public static void main(final String[] args) throws Exception {

        final FileSystemManager fsManager = VFS.getManager();
        final FileObject dir = fsManager.toFileObject(new File("."));

        // We are interested in files older than one day
        final long cutoff = System.currentTimeMillis() - (24 * 60 * 60 * 1000);
        final AgeFileFilter filter = new AgeFileFilter(cutoff);

        final FileObject[] files = dir.findFiles(new FileFilterSelector(filter));
        for (FileObject file : files) {
            System.out.println(file);
        }

    }
 
Example #27
Source File: FileNamePerformance.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
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");
}
 
Example #28
Source File: RepositoryVfsProvider.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
private void registerRepoVFS() {
  FileSystemManager fsm = KettleVFS.getInstance().getFileSystemManager();
  if ( fsm instanceof DefaultFileSystemManager ) {
    try {
      ( (DefaultFileSystemManager) fsm ).addProvider( SCHEME, this );
      final Spoon spoon = Spoon.getInstance();
      System.out.println(  );
    } catch ( Exception ex ) {
      throw new RuntimeException( "Error initialize repo:// VFS", ex );
    }
  }
}
 
Example #29
Source File: ConversionTestCase.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
@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()));
}
 
Example #30
Source File: VFSFileSystem.java    From commons-configuration with Apache License 2.0 5 votes vote down vote up
@Override
public URL getURL(final String basePath, final String file) throws MalformedURLException
{
    if ((basePath != null && UriParser.extractScheme(basePath) == null)
        || (basePath == null && UriParser.extractScheme(file) == null))
    {
        return super.getURL(basePath, file);
    }
    try
    {
        final FileSystemManager fsManager = VFS.getManager();

        FileName path;
        if (basePath != null && UriParser.extractScheme(file) == null)
        {
            final FileName base = fsManager.resolveURI(basePath);
            path = fsManager.resolveName(base, file);
        }
        else
        {
            path = fsManager.resolveURI(file);
        }

        final URLStreamHandler handler = new VFSURLStreamHandler(path);
        return new URL(null, path.getURI(), handler);
    }
    catch (final FileSystemException fse)
    {
        throw new ConfigurationRuntimeException("Could not parse basePath: " + basePath
            + " and fileName: " + file, fse);
    }
}