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

The following examples show how to use org.apache.commons.vfs2.FileObject#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: ProviderWriteTests.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Tests file copy to and from the same file system 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");
    assertFalse(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");
    assertFalse(fileCopy.exists());
    fileCopy.copyFrom(file, Selectors.SELECT_SELF);

    assertSameContent(content, fileCopy);
}
 
Example 2
Source File: CommonPaths.java    From spoofax with Apache License 2.0 6 votes vote down vote up
@Nullable protected FileObject find(Iterable<FileObject> dirs, String relativePath) {
    FileObject file = null;
    for(FileObject dir : dirs) {
        try {
            FileObject candidate = dir.resolveFile(relativePath);
            if(candidate.exists()) {
                if(file != null) {
                    throw new MetaborgRuntimeException("Found multiple candidates for " + relativePath);
                } else {
                    file = candidate;
                }
            }
        } catch(FileSystemException e) {
            logger.warn("Error when trying to resolve {} in {}", e, relativePath, dir);
        }
    }
    return file;
}
 
Example 3
Source File: FileObjectContentLocation.java    From pentaho-kettle with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the content entity with the given name. If the entity does not exist, an Exception will be raised.
 *
 * @param name the name of the entity to be retrieved.
 * @return the content entity for this name, never null.
 * @throws ContentIOException if an repository error occured.
 */
public ContentEntity getEntry( final String name ) throws ContentIOException {
  try {
    if ( RepositoryUtilities.isInvalidPathName( name ) ) {
      throw new IllegalArgumentException( "The name given is not valid." );
    }

    final FileObject file = getBackend();
    final FileObject child = file.resolveFile( name );
    if ( child.exists() == false ) {
      throw new ContentIOException( "Not found:" + child );
    }

    if ( child.isFolder() ) {
      return new FileObjectContentLocation( this, child );
    } else if ( child.isFile() ) {
      return new FileObjectContentItem( this, child );
    } else {
      throw new ContentIOException( "Not File nor directory." );
    }
  } catch ( FileSystemException e ) {
    throw new RuntimeException( e );
  }
}
 
Example 4
Source File: OldVFSNotebookRepo.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
private Note getNote(FileObject noteDir) throws IOException {
  if (!isDirectory(noteDir)) {
    throw new IOException(noteDir.getName().toString() + " is not a directory");
  }

  FileObject noteJson = noteDir.resolveFile("note.json", NameScope.CHILD);
  if (!noteJson.exists()) {
    throw new IOException(noteJson.getName().toString() + " not found");
  }
  
  FileContent content = noteJson.getContent();
  InputStream ins = content.getInputStream();
  String json = IOUtils.toString(ins, conf.getString(ConfVars.ZEPPELIN_ENCODING));
  ins.close();

  return Note.fromJson(json);
}
 
Example 5
Source File: ProviderRenameTests.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
private void moveFile(final FileObject scratchFolder, final FileObject file, final String content)
        throws FileSystemException, Exception {
    final FileObject fileMove = scratchFolder.resolveFile("file1move.txt");
    assertFalse(fileMove.exists());

    file.moveTo(fileMove);

    assertFalse(file.exists());
    assertTrue(fileMove.exists());

    assertSameContent(content, fileMove);

    // Delete the file.
    assertTrue(fileMove.exists());
    assertTrue(fileMove.delete());
}
 
Example 6
Source File: FTPRemoteLocationExecutorDelegate.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@Override
public boolean move(String sourceFile, String targetDir, boolean overwriteFile) throws IOException {
  FileObject targetFolder = resolveChild(targetDir);
  targetFolder.createFolder();

  String targetFileName = StringUtils.appendIfMissing(targetFolder.getName().getPath(), "/")
      + StringUtils.substringAfterLast(sourceFile, "/");

  FileObject targetFile = targetFolder.resolveFile(targetFileName, NameScope.DESCENDENT);

  if (!overwriteFile && targetFile.exists()) {
    return false;
  }

  resolveChild(sourceFile).moveTo(targetFile);
  targetFile.close();


  return true;
}
 
Example 7
Source File: ContentTests.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * 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());
    assertFalse("child does not exist", child.exists());
    assertSame(folder, child.getParent());

    // Test when neither exists
    folder = getReadFolder().resolveFile("unknown-folder");
    child = folder.resolveFile("unknown-file");
    assertFalse("folder does not exist", folder.exists());
    assertFalse("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());
    }
}
 
Example 8
Source File: ProviderWriteAppendTests.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * 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");
    assertFalse(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");
    assertFalse(fileCopy.exists());
    fileCopy.copyFrom(file, Selectors.SELECT_SELF);

    assertSameContent(contentAppend, fileCopy);

    // Delete the file.
    assertTrue(fileCopy.exists());
    assertTrue(fileCopy.delete());
}
 
Example 9
Source File: ProviderWriteTests.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Tests folder creation.
 */
public void testFolderCreate() throws Exception {
    final FileObject scratchFolder = createScratchFolder();

    // Create direct child of the test folder
    FileObject folder = scratchFolder.resolveFile("dir1");
    assertFalse(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");
    assertFalse(folder.exists());
    assertFalse(folder.getParent().exists());
    assertFalse(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();
}
 
Example 10
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 11
Source File: DefaultURLStreamHandler.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
@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(context.getFileSystemManager().getSchemes(), 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());
    }
}
 
Example 12
Source File: VFSClassLoader.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * 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<>(2);

    for (final FileObject baseFile : resources) {
        try (final FileObject file = baseFile.resolveFile(name, NameScope.DESCENDENT_OR_SELF)) {
            if (FileObjectUtils.exists(file)) {
                result.add(new Resource(name, baseFile, file).getURL());
            }
        }
    }

    return Collections.enumeration(result);
}
 
Example 13
Source File: ProviderDeleteTests.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * deletes a single file
 */
public void testDeleteFile() throws Exception {
    final FileObject scratchFolder = createScratchFolder();

    final FileObject file = scratchFolder.resolveFile("dir1/a.txt");

    assertTrue(file.delete());
}
 
Example 14
Source File: Shell.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example 15
Source File: ProviderCacheStrategyTests.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * 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");
}
 
Example 16
Source File: OldVFSNotebookRepo.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Override
public Note get(String noteId, AuthenticationInfo subject) throws IOException {
  FileObject rootDir = fsManager.resolveFile(getPath("/"));
  FileObject noteDir = rootDir.resolveFile(noteId, NameScope.CHILD);

  return getNote(noteDir);
}
 
Example 17
Source File: ProjectConfigService.java    From spoofax with Apache License 2.0 4 votes vote down vote up
@Override protected FileObject getConfigFile(FileObject rootFolder) throws FileSystemException {
    return rootFolder.resolveFile(MetaborgConstants.FILE_CONFIG);
}
 
Example 18
Source File: LanguageComponentConfigService.java    From spoofax with Apache License 2.0 4 votes vote down vote up
@Override protected FileObject getConfigFile(FileObject rootFolder) throws FileSystemException {
    return rootFolder.resolveFile(MetaborgConstants.LOC_COMPONENT_CONFIG);
}
 
Example 19
Source File: ProviderWriteTests.java    From commons-vfs with Apache License 2.0 4 votes vote down vote up
/**
 * 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");
    assertFalse(file.exists());
    file.createFile();
    assertTrue(file.exists());
    assertSame(FileType.FILE, file.getType());
    assertTrue(file.isFile());
    assertEquals(0, file.getContent().getSize());
    assertTrue(file.getContent().isEmpty());
    assertFalse(file.isHidden());
    assertFalse(file.isSymbolicLink());
    assertTrue(file.isReadable());
    assertTrue(file.isWriteable());

    // Create direct child of the test folder - special name
    file = scratchFolder.resolveFile("file1%25.txt");
    assertFalse(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");
    assertFalse(file.exists());
    assertFalse(file.getParent().exists());
    assertFalse(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());
}
 
Example 20
Source File: LRUFilesCacheTests.java    From commons-vfs with Apache License 2.0 4 votes vote down vote up
public void testFilesCache() throws Exception {
    final FileObject scratchFolder = getWriteFolder();
    Assert.assertNotNull("scratchFolder", scratchFolder);

    // 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");
    assertSame(dir2, dir2_2);

    // check if the cache still holds the right instance
    final FileObject dir1_2 = scratchFolder.resolveFile("dir1");
    assertNotSame(dir1, dir1_2);
}