Java Code Examples for org.apache.commons.vfs2.FileSystemManager

The following examples show how to use org.apache.commons.vfs2.FileSystemManager. These examples are extracted from open source projects. 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 Project: commons-vfs   Source File: Http4FilesCacheTestCase.java    License: 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 2
Source Project: o2oa   Source File: StorageObject.java    License: 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 3
Source Project: spoofax   Source File: DefaultFileSystemManagerProvider.java    License: 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 4
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 5
Source Project: jbake   Source File: BakeWatcher.java    License: 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 6
Source Project: commons-vfs   Source File: VFSClassLoader.java    License: 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 7
Source Project: commons-vfs   Source File: FileNamePerformance.java    License: 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 8
/**
 * 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 9
Source Project: commons-vfs   Source File: ZipFileObjectTestCase.java    License: 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 10
Source Project: commons-configuration   Source File: VFSFileSystem.java    License: 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 11
Source Project: commons-vfs   Source File: UrlTests.java    License: 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 Project: commons-vfs   Source File: RamProviderTestCase.java    License: 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 13
Source Project: commons-vfs   Source File: AbstractSftpProviderTestCase.java    License: 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 14
/**
 * 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 15
Source Project: commons-vfs   Source File: DefaultFileContentTest.java    License: 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 16
Source Project: micro-integrator   Source File: FilePollingConsumer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Acquire distributed lock if required first, then do the file level locking
 *
 * @param fsManager
 * @param fileObject
 * @return
 */
private boolean acquireLock(FileSystemManager fsManager, FileObject fileObject) {
    String strContext = fileObject.getName().getURI();
    boolean rtnValue = false;

    // When processing a directory list is fetched initially. Therefore
    // there is still a chance of file processed by another process.
    // Need to check the source file before processing.
    try {
        String parentURI = fileObject.getParent().getName().getURI();
        if (parentURI.contains("?")) {
            String suffix = parentURI.substring(parentURI.indexOf("?"));
            strContext += suffix;
        }
        FileObject sourceFile = fsManager.resolveFile(strContext, fso);
        if (!sourceFile.exists()) {
            return false;
        }
    } catch (FileSystemException e) {
        return false;
    }
    VFSParamDTO vfsParamDTO = new VFSParamDTO();
    vfsParamDTO.setAutoLockRelease(autoLockRelease);
    vfsParamDTO.setAutoLockReleaseSameNode(autoLockReleaseSameNode);
    vfsParamDTO.setAutoLockReleaseInterval(autoLockReleaseInterval);
    rtnValue = VFSUtils.acquireLock(fsManager, fileObject, vfsParamDTO, fso, true);

    return rtnValue;
}
 
Example 17
Source Project: o2oa   Source File: StorageObject.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
private FileSystemManager getFileSystemManager() throws Exception {
	if (FILESYSTEMANAGERINSTANCE == null) {
		synchronized (StorageObject.class) {
			if (FILESYSTEMANAGERINSTANCE == null) {
				StandardFileSystemManager fs = new StandardFileSystemManager();
				fs.setFilesCache(new NullFilesCache());
				fs.setCacheStrategy(CacheStrategy.ON_RESOLVE);
				fs.init();
				FILESYSTEMANAGERINSTANCE = fs;
			}
		}
	}
	return FILESYSTEMANAGERINSTANCE;
}
 
Example 18
Source Project: o2oa   Source File: StorageObject.java    License: GNU Affero General Public License v3.0 5 votes vote down vote up
/** 更新Content内容 */
public Long updateContent(StorageMapping mapping, InputStream input) throws Exception {
	long length = -1L;
	FileSystemManager manager = this.getFileSystemManager();
	String prefix = this.getPrefix(mapping);
	String path = this.path();
	if (StringUtils.isEmpty(path)) {
		throw new Exception("path can not be empty.");
	}
	FileSystemOptions options = this.getOptions(mapping);
	try (ByteArrayOutputStream baos = new ByteArrayOutputStream()) {
		/* 由于可以在传输过程中取消传输,先拷贝到内存 */
		IOUtils.copyLarge(input, baos);
		try (FileObject fo = manager.resolveFile(prefix + PATHSEPARATOR + path, options);
				OutputStream output = fo.getContent().getOutputStream()) {
			length = IOUtils.copyLarge(new ByteArrayInputStream(baos.toByteArray()), output);
			this.setLength(length);
			if (!Objects.equals(StorageProtocol.webdav, mapping.getProtocol())) {
				/* webdav关闭会试图去关闭commons.httpClient */
				manager.closeFileSystem(fo.getFileSystem());
			}
		}
	}
	this.setStorage(mapping.getName());
	this.setLastUpdateTime(new Date());
	return length;
}
 
Example 19
Source Project: commons-vfs   Source File: VfsClassLoaderTests.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Tests retrieving resources (from local directory with .jar extension).
 * <p>
 * This test is repeated with various provider configurations but works on local files, only.
 * </p>
 */
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 (final 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");
    assertSame("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"));
}
 
Example 20
Source Project: metron   Source File: VFSClassloaderUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Resolve a set of URIs into FileObject objects.
 * This is not recursive. The URIs can refer directly to a file or directory or an optional regex at the end.
 * (NOTE: This is NOT a glob).
 * @param vfs The file system manager to use to resolve URIs
 * @param uris comma separated URIs and URI + globs
 * @return
 * @throws FileSystemException
 */
static FileObject[] resolve(FileSystemManager vfs, String uris) throws FileSystemException {
  if (uris == null) {
    return new FileObject[0];
  }

  ArrayList<FileObject> classpath = new ArrayList<>();
  for (String path : uris.split(",")) {
    path = path.trim();
    if (path.equals("")) {
      continue;
    }
    FileObject fo = vfs.resolveFile(path);
    switch (fo.getType()) {
      case FILE:
      case FOLDER:
        classpath.add(fo);
        break;
      case IMAGINARY:
        // assume its a pattern
        String pattern = fo.getName().getBaseName();
        if (fo.getParent() != null && fo.getParent().getType() == FileType.FOLDER) {
          FileObject[] children = fo.getParent().getChildren();
          for (FileObject child : children) {
            if (child.getType() == FileType.FILE && child.getName().getBaseName().matches(pattern)) {
              classpath.add(child);
            }
          }
        } else {
          LOG.warn("ignoring classpath entry {}", fo);
        }
        break;
      default:
        LOG.warn("ignoring classpath entry {}", fo);
        break;
    }
  }
  return classpath.toArray(new FileObject[classpath.size()]);
}
 
Example 21
Source Project: tutorials   Source File: SftpFileTransferLiveTest.java    License: MIT License 5 votes vote down vote up
@Test
public void whenUploadFileUsingApacheVfs_thenSuccess() throws IOException {
    FileSystemManager manager = VFS.getManager();
    FileObject local = manager.resolveFile(System.getProperty("user.dir") + "/" + localFile);
    FileObject remote = manager.resolveFile("sftp://" + username + ":" + password + "@" + remoteHost + "/" + remoteDir + "vfsFile.txt");
    remote.copyFrom(local, Selectors.SELECT_SELF);
    local.close();
    remote.close();
}
 
Example 22
Source Project: tutorials   Source File: SftpFileTransferLiveTest.java    License: MIT License 5 votes vote down vote up
@Test
public void whenDownloadFileUsingApacheVfs_thenSuccess() throws IOException {
    FileSystemManager manager = VFS.getManager();
    FileObject local = manager.resolveFile(System.getProperty("user.dir") + "/" + localDir + "vfsFile.txt");
    FileObject remote = manager.resolveFile("sftp://" + username + ":" + password + "@" + remoteHost + "/" + remoteFile);
    local.copyFrom(remote, Selectors.SELECT_SELF);
    local.close();
    remote.close();
}
 
Example 23
Source Project: commons-vfs   Source File: WebdavProviderTestCase.java    License: 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 {
    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);
}
 
Example 24
Source Project: commons-vfs   Source File: FileNamePerformance.java    License: 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 25
Source Project: commons-vfs   Source File: FileFileFilterExample.java    License: 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 Project: commons-configuration   Source File: VFSFileSystem.java    License: 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);
    }
}
 
Example 27
Source Project: commons-vfs   Source File: ZipProviderTestCase.java    License: 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 28
Source Project: commons-vfs   Source File: Webdav4ProviderTestCase.java    License: 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 {
    String uri = getSystemTestUriOverride();
    if (uri == null) {
        uri = ConnectionUri;
    }
    final Webdav4FileSystemConfigBuilder builder = (Webdav4FileSystemConfigBuilder) manager
            .getFileSystemConfigBuilder("webdav4");
    final FileSystemOptions opts = new FileSystemOptions();
    builder.setRootURI(opts, uri);
    return manager.resolveFile(uri, opts);
}
 
Example 29
Source Project: commons-vfs   Source File: DirectoryFileFilterExample.java    License: 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 30
Source Project: commons-vfs   Source File: ZipFileObjectTestCase.java    License: 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);
}