Java Code Examples for org.apache.commons.vfs2.FileSystemManager#resolveFile()

The following examples show how to use org.apache.commons.vfs2.FileSystemManager#resolveFile() . 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: NestedTarTestCase.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 {
    // 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("/");
}
 
Example 2
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 3
Source File: ZipProviderWithCharsetTestCase.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 the same charset as the default but we exercise having a Charset set.
    builder.setCharset(opts, StandardCharsets.UTF_8);

    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.assertEquals(StandardCharsets.UTF_8, zipFileSystem.getCharset());
    return resolvedFile;
}
 
Example 4
Source File: StorageObject.java    From o2oa with GNU Affero General Public License v3.0 6 votes vote down vote up
/** 将内容流出到output */
public Long readContent(StorageMapping mapping, OutputStream output) throws Exception {
	long length = -1L;
	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()) {
			try (InputStream input = fo.getContent().getInputStream()) {
				length = IOUtils.copyLarge(input, output);
			}
		} else {
			throw new Exception(fo.getPublicURIString() + " not existed, object:" + this.toString() + ".");
		}
		manager.closeFileSystem(fo.getFileSystem());
	}
	return length;
}
 
Example 5
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 6
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 7
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 8
Source File: Webdav4ProviderTestCase.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 {
    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 9
Source File: SftpFileTransferLiveTest.java    From tutorials with 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 10
Source File: UrlProviderHttpTestCase.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 {
    String uri = getSystemTestUriOverride();
    if (uri == null) {
        uri = ConnectionUri;
    }
    return manager.resolveFile(uri);
}
 
Example 11
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 12
Source File: Http5GetContentInfoTest.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Tests VFS-427 NPE on Http5FileObject.getContent().getContentInfo().
 *
 * @throws FileSystemException thrown when the getContentInfo API fails.
 */
@Test
public void testGetContentInfo() throws FileSystemException {
    final FileSystemManager fsManager = VFS.getManager();
    final FileObject fo = fsManager.resolveFile("http5://www.apache.org/licenses/LICENSE-2.0.txt");
    final FileContent content = fo.getContent();
    Assert.assertNotNull(content);
    // Used to NPE before fix:
    content.getContentInfo();
}
 
Example 13
Source File: VFSClassloaderUtil.java    From metron with 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 14
Source File: DefaultFileContentTest.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
private void testOutputStreamBufferSize(final int bufferSize) throws Exception {
    final File temp = File.createTempFile("temp-file-name", ".tmp");
    final FileSystemManager fileSystemManager = VFS.getManager();

    try (FileObject file = fileSystemManager.resolveFile(temp.getAbsolutePath())) {
        file.getContent().getOutputStream(bufferSize).close();
    }
}
 
Example 15
Source File: Http5ProviderTestCase.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 {
    String uri = getSystemTestUriOverride();
    if (uri == null) {
        uri = ConnectionUri;
    }
    return manager.resolveFile(uri);
}
 
Example 16
Source File: DefaultFileContentTest.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
@Test(expected = IllegalArgumentException.class)
public void testOutputStreamBufferSizeNegativeWithAppendFlag() throws Exception {
    final File temp = File.createTempFile("temp-file-name", ".tmp");
    final FileSystemManager fileSystemManager = VFS.getManager();

    try (FileObject file = fileSystemManager.resolveFile(temp.getAbsolutePath())) {
        file.getContent().getOutputStream(true, -1);
    }
}
 
Example 17
Source File: SmbProviderTestCase.java    From commons-vfs with Apache License 2.0 4 votes vote down vote up
/**
 * 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);
}
 
Example 18
Source File: JarProviderTestCase.java    From commons-vfs with Apache License 2.0 4 votes vote down vote up
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);
}
 
Example 19
Source File: SftpProviderStreamProxyModeTestCase.java    From commons-vfs with Apache License 2.0 4 votes vote down vote up
@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 FileSystemOptions proxyOptions = (FileSystemOptions) fileSystemOptions.clone();

    final URI parsedURI = new URI(uri);
    final String userInfo = parsedURI.getUserInfo();
    final String[] userFields = userInfo == null ? null : userInfo.split(":", 2);

    builder.setProxyType(fileSystemOptions, SftpFileSystemConfigBuilder.PROXY_STREAM);
    if (userFields != null) {
        if (userFields.length > 0) {
            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
    if (userInfo == null) {
        uri = String.format("sftp://localhost:%d", parsedURI.getPort());
    } else {
        uri = String.format("sftp://%s@localhost:%d", userInfo, parsedURI.getPort());
    }


    final FileObject fileObject = manager.resolveFile(uri, fileSystemOptions);
    this.fileSystem = (SftpFileSystem) fileObject.getFileSystem();
    return fileObject;
}
 
Example 20
Source File: FileNamePerformance.java    From commons-vfs with Apache License 2.0 3 votes vote down vote up
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:[email protected]/vfsusr");
    final FileName rootName = root.getName();

    testNames(mgr, rootName);

    testChildren(root);

    testFiles(mgr);
}