org.apache.commons.vfs2.NameScope Java Examples

The following examples show how to use org.apache.commons.vfs2.NameScope. 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: 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 #2
Source File: OldVFSNotebookRepo.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void save(Note note, AuthenticationInfo subject) throws IOException {
  LOG.info("Saving note:" + note.getId());
  String json = note.toJson();

  FileObject rootDir = getRootDir();

  FileObject noteDir = rootDir.resolveFile(note.getId(), NameScope.CHILD);

  if (!noteDir.exists()) {
    noteDir.createFolder();
  }
  if (!isDirectory(noteDir)) {
    throw new IOException(noteDir.getName().toString() + " is not a directory");
  }

  FileObject noteJson = noteDir.resolveFile(".note.json", NameScope.CHILD);
  // false means not appending. creates file if not exists
  OutputStream out = noteJson.getContent().getOutputStream(false);
  out.write(json.getBytes(conf.getString(ConfVars.ZEPPELIN_ENCODING)));
  out.close();
  noteJson.moveTo(noteDir.resolveFile("note.json", NameScope.CHILD));
}
 
Example #3
Source File: OldVFSNotebookRepo.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Override
public void remove(String noteId, AuthenticationInfo subject) throws IOException {
  FileObject rootDir = fsManager.resolveFile(getPath("/"));
  FileObject noteDir = rootDir.resolveFile(noteId, NameScope.CHILD);

  if (!noteDir.exists()) {
    // nothing to do
    return;
  }

  if (!isDirectory(noteDir)) {
    // it is not look like zeppelin note savings
    throw new IOException("Can not remove " + noteDir.getName().toString());
  }

  noteDir.delete(Selectors.SELECT_SELF_AND_CHILDREN);
}
 
Example #4
Source File: NamingTests.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Tests resolution of absolute names.
 */
private void checkAbsoluteNames(final FileName name) throws Exception {
    // Root
    assertSameName("/", name, "/");
    assertSameName("/", name, "//");
    assertSameName("/", name, "/.");
    assertSameName("/", name, "/some file/..");

    // Some absolute names
    assertSameName("/a", name, "/a");
    assertSameName("/a", name, "/./a");
    assertSameName("/a", name, "/a/.");
    assertSameName("/a/b", name, "/a/b");

    // Some bad names
    assertBadName(name, "/..", NameScope.FILE_SYSTEM);
    assertBadName(name, "/a/../..", NameScope.FILE_SYSTEM);
}
 
Example #5
Source File: VFSNotebookRepo.java    From zeppelin with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void save(Note note, AuthenticationInfo subject) throws IOException {
  LOGGER.info("Saving note " + note.getId() + " to " + buildNoteFileName(note));
  // write to tmp file first, then rename it to the {note_name}_{note_id}.zpln
  FileObject noteJson = rootNotebookFileObject.resolveFile(
      buildNoteTempFileName(note), NameScope.DESCENDENT);
  OutputStream out = null;
  try {
    out = noteJson.getContent().getOutputStream(false);
    IOUtils.write(note.toJson().getBytes(conf.getString(ConfVars.ZEPPELIN_ENCODING)), out);
  } finally {
    if (out != null) {
      out.close();
    }
  }
  noteJson.moveTo(rootNotebookFileObject.resolveFile(
      buildNoteFileName(note), NameScope.DESCENDENT));
}
 
Example #6
Source File: NamingTests.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Tests descendent name resolution.
 */
public void testDescendentName() throws Exception {
    final FileName baseName = getReadFolder().getName();

    // Test direct child
    String path = baseName.getPath() + "/some-child";
    assertSameName(path, baseName, "some-child", NameScope.DESCENDENT);

    // Test compound name
    path = path + "/grand-child";
    assertSameName(path, baseName, "some-child/grand-child", NameScope.DESCENDENT);

    // Test relative names
    assertSameName(path, baseName, "./some-child/grand-child", NameScope.DESCENDENT);
    assertSameName(path, baseName, "./nada/../some-child/grand-child", NameScope.DESCENDENT);
    assertSameName(path, baseName, "some-child/./grand-child", NameScope.DESCENDENT);

    // Test badly formed descendent names
    checkDescendentNames(baseName, NameScope.DESCENDENT);
}
 
Example #7
Source File: NamingTests.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Checks that a relative name resolves to the expected absolute path. Tests both forward and back slashes.
 */
private void assertSameName(final String expectedPath, final FileName baseName, final String relName,
        final NameScope scope) throws Exception {
    // Try the supplied name
    FileName name = getManager().resolveName(baseName, relName, scope);
    assertEquals(expectedPath, name.getPath());

    String temp;

    // Replace the separators
    temp = relName.replace('\\', '/');
    name = getManager().resolveName(baseName, temp, scope);
    assertEquals(expectedPath, name.getPath());

    // And again
    temp = relName.replace('/', '\\');
    name = getManager().resolveName(baseName, temp, scope);
    assertEquals(expectedPath, name.getPath());
}
 
Example #8
Source File: NamingTests.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Tests child file names.
 */
public void testChildName() throws Exception {
    final FileName baseName = getReadFolder().getName();
    final String basePath = baseName.getPath();
    final FileName name = getManager().resolveName(baseName, "some-child", NameScope.CHILD);

    // Test path is absolute
    assertTrue("is absolute", basePath.startsWith("/"));

    // Test base name
    assertEquals("base name", "some-child", name.getBaseName());

    // Test absolute path
    assertEquals("absolute path", basePath + "/some-child", name.getPath());

    // Test parent path
    assertEquals("parent absolute path", basePath, name.getParent().getPath());

    // Try using a compound name to find a child
    assertBadName(name, "a/b", NameScope.CHILD);

    // Check other invalid names
    checkDescendentNames(name, NameScope.CHILD);
}
 
Example #9
Source File: VirtualFileSystem.java    From commons-vfs with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a file object. This method is called only if the requested file is not cached.
 */
@Override
protected FileObject createFile(final AbstractFileName name) throws Exception {
    // Find the file that the name points to
    final FileName junctionPoint = getJunctionForFile(name);
    final FileObject file;
    if (junctionPoint != null) {
        // Resolve the real file
        final FileObject junctionFile = junctions.get(junctionPoint);
        final String relName = junctionPoint.getRelativeName(name);
        file = junctionFile.resolveFile(relName, NameScope.DESCENDENT_OR_SELF);
    } else {
        file = null;
    }

    // Return a wrapper around the file
    return new DelegateFileObject(name, this, file);
}
 
Example #10
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 #11
Source File: AbstractFileObject.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Copies another file to this file.
 *
 * @param file The FileObject to copy.
 * @param selector The FileSelector.
 * @throws FileSystemException if an error occurs.
 */
@Override
public void copyFrom(final FileObject file, final FileSelector selector) throws FileSystemException {
    if (!FileObjectUtils.exists(file)) {
        throw new FileSystemException("vfs.provider/copy-missing-file.error", file);
    }

    // Locate the files to copy across
    final ArrayList<FileObject> files = new ArrayList<>();
    file.findFiles(selector, false, files);

    // Copy everything across
    for (final FileObject srcFile : files) {
        // Determine the destination file
        final String relPath = file.getName().getRelativeName(srcFile.getName());
        final FileObject destFile = resolveFile(relPath, NameScope.DESCENDENT_OR_SELF);

        // Clean up the destination file, if necessary
        if (FileObjectUtils.exists(destFile) && destFile.getType() != srcFile.getType()) {
            // The destination file exists, and is not of the same type,
            // so delete it
            // TODO - add a pluggable policy for deleting and overwriting existing files
            destFile.deleteAll();
        }

        // Copy across
        try {
            if (srcFile.getType().hasContent()) {
                FileObjectUtils.writeContent(srcFile, destFile);
            } else if (srcFile.getType().hasChildren()) {
                destFile.createFolder();
            }
        } catch (final IOException e) {
            throw new FileSystemException("vfs.provider/copy-file.error", e, srcFile, destFile);
        }
    }
}
 
Example #12
Source File: FileObject.java    From obevo with Apache License 2.0 5 votes vote down vote up
@Override
public FileObject resolveFile(String name, NameScope scope) {
    try {
        return FileObject.toDaFileObject(this.fileObject.resolveFile(name, scope));
    } catch (FileSystemException e) {
        throw new VFSFileSystemException(e);
    }
}
 
Example #13
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 #14
Source File: VFSClassLoader.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Searches through the search path of for the first class or resource with specified name.
 *
 * @param name The resource to load.
 * @return The Resource.
 * @throws FileSystemException if an error occurs.
 */
private Resource loadResource(final String name) throws FileSystemException {
    for (final FileObject baseFile : resources) {
        try (final FileObject file = baseFile.resolveFile(name, NameScope.DESCENDENT_OR_SELF)) {
            if (FileObjectUtils.exists(file)) {
                return new Resource(name, baseFile, file);
            }
        }
    }
    return null;
}
 
Example #15
Source File: DefaultFileSystemManager.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Resolve the uri to a file name.
 *
 * @param uri The URI to resolve.
 * @return The FileName of the file.
 * @throws FileSystemException if an error occurs.
 */
@Override
public FileName resolveURI(final String uri) throws FileSystemException {
    UriParser.checkUriEncoding(uri);

    if (uri == null) {
        throw new IllegalArgumentException();
    }

    // Extract the scheme
    final String scheme = UriParser.extractScheme(getSchemes(), uri);
    if (scheme != null) {
        // An absolute URI - locate the provider
        final FileProvider provider = providers.get(scheme);
        if (provider != null) {
            return provider.parseUri(null, uri);
        }

        // Otherwise, assume a local file
    }

    // Handle absolute file names
    if (localFileProvider != null && localFileProvider.isAbsoluteLocalName(uri)) {
        return localFileProvider.parseUri(null, uri);
    }

    if (scheme != null) {
        // An unknown scheme - hand it to the default provider
        FileSystemException.requireNonNull(defaultProvider, "vfs.impl/unknown-scheme.error", scheme, uri);
        return defaultProvider.parseUri(null, uri);
    }

    // Assume a relative name - use the supplied base file
    FileSystemException.requireNonNull(baseFile, "vfs.impl/find-rel-file.error", uri);

    return resolveName(baseFile.getName(), uri, NameScope.FILE_SYSTEM);
}
 
Example #16
Source File: ContentTests.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts every file in a folder exists and has the expected content.
 */
private void assertSameContent(final FileInfo expected, final FileObject folder) throws Exception {
    for (final FileInfo fileInfo : expected.children.values()) {
        final FileObject child = folder.resolveFile(fileInfo.baseName, NameScope.CHILD);

        assertTrue(child.getName().toString(), child.exists());
        if (fileInfo.type == FileType.FILE) {
            assertSameContent(fileInfo.content, child);
        } else {
            assertSameContent(fileInfo, child);
        }
    }
}
 
Example #17
Source File: NamingTests.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Name resolution tests that are common for CHILD or DESCENDENT scope.
 */
private void checkDescendentNames(final FileName name, final NameScope scope) throws Exception {
    // Make some assumptions about the name
    assertFalse(name.getPath().equals("/"));
    assertFalse(name.getPath().endsWith("/a"));
    assertFalse(name.getPath().endsWith("/a/b"));

    // Test names with the same prefix
    final String path = name.getPath() + "/a";
    assertSameName(path, name, path, scope);
    assertSameName(path, name, "../" + name.getBaseName() + "/a", scope);

    // Test an empty name
    assertBadName(name, "", scope);

    // Test . name
    assertBadName(name, ".", scope);
    assertBadName(name, "./", scope);

    // Test ancestor names
    assertBadName(name, "..", scope);
    assertBadName(name, "../a", scope);
    assertBadName(name, "../" + name.getBaseName() + "a", scope);
    assertBadName(name, "a/..", scope);

    // Test absolute names
    assertBadName(name, "/", scope);
    assertBadName(name, "/a", scope);
    assertBadName(name, "/a/b", scope);
    assertBadName(name, name.getPath(), scope);
    assertBadName(name, name.getPath() + "a", scope);
}
 
Example #18
Source File: NamingTests.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Asserts that a particular relative name is invalid for a particular scope.
 */
private void assertBadName(final FileName name, final String relName, final NameScope scope) {
    try {
        getManager().resolveName(name, relName, scope);
        fail("expected failure");
    } catch (final FileSystemException e) {
        // TODO - should check error message
    }
}
 
Example #19
Source File: ConcurrentFileSystemManager.java    From pentaho-kettle with Apache License 2.0 5 votes vote down vote up
@Override
public FileName resolveName( FileName base, String name, NameScope scope ) throws FileSystemException {
  lock.readLock().lock();
  try {
    return super.resolveName( base, name, scope );
  } finally {
    lock.readLock().unlock();
  }
}
 
Example #20
Source File: AbstractFileName.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Determines if another file name is a descendent of this file name.
 *
 * @param descendent The FileName to check.
 * @param scope The NameScope.
 * @return true if the FileName is a descendent, false otherwise.
 */
@Override
public boolean isDescendent(final FileName descendent, final NameScope scope) {
    if (!descendent.getRootURI().equals(getRootURI())) {
        return false;
    }
    return checkName(getPath(), descendent.getPath(), scope);
}
 
Example #21
Source File: AbstractFileName.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Checks whether a path fits in a particular scope of another path.
 *
 * @param basePath An absolute, normalised path.
 * @param path An absolute, normalised path.
 * @param scope The NameScope.
 * @return true if the path fits in the scope, false otherwise.
 */
public static boolean checkName(final String basePath, final String path, final NameScope scope) {
    if (scope == NameScope.FILE_SYSTEM) {
        // All good
        return true;
    }

    if (!path.startsWith(basePath)) {
        return false;
    }

    int baseLen = basePath.length();
    if (VFS.isUriStyle()) {
        // strip the trailing "/"
        baseLen--;
    }

    if (scope == NameScope.CHILD) {
        if (path.length() == baseLen || baseLen > 1 && path.charAt(baseLen) != SEPARATOR_CHAR
                || path.indexOf(SEPARATOR_CHAR, baseLen + 1) != -1) {
            return false;
        }
    } else if (scope == NameScope.DESCENDENT) {
        if (path.length() == baseLen || baseLen > 1 && path.charAt(baseLen) != SEPARATOR_CHAR) {
            return false;
        }
    } else if (scope == NameScope.DESCENDENT_OR_SELF) {
        if (baseLen > 1 && path.length() > baseLen && path.charAt(baseLen) != SEPARATOR_CHAR) {
            return false;
        }
    } else if (scope != NameScope.FILE_SYSTEM) {
        throw new IllegalArgumentException();
    }

    return true;
}
 
Example #22
Source File: AbstractFileName.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Determines if another file name is an ancestor of this file name.
 *
 * @param ancestor The FileName to check.
 * @return true if the FileName is an ancestor, false otherwise.
 */
@Override
public boolean isAncestor(final FileName ancestor) {
    if (!ancestor.getRootURI().equals(getRootURI())) {
        return false;
    }
    return checkName(ancestor.getPath(), getPath(), NameScope.DESCENDENT);
}
 
Example #23
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 #24
Source File: VFSNotebookRepo.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Override
public Note get(String noteId, String notePath, AuthenticationInfo subject) throws IOException {
  FileObject noteFile = rootNotebookFileObject.resolveFile(buildNoteFileName(noteId, notePath),
      NameScope.DESCENDENT);
  String json = IOUtils.toString(noteFile.getContent().getInputStream(),
      conf.getString(ConfVars.ZEPPELIN_ENCODING));
  Note note = Note.fromJson(json);
  // setPath here just for testing, because actually NoteManager will setPath
  note.setPath(notePath);
  return note;
}
 
Example #25
Source File: VFSNotebookRepo.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Override
public void move(String noteId,
                 String notePath,
                 String newNotePath,
                 AuthenticationInfo subject) throws IOException {
  LOGGER.info("Move note " + noteId + " from " + notePath + " to " + newNotePath);
  FileObject fileObject = rootNotebookFileObject.resolveFile(
      buildNoteFileName(noteId, notePath), NameScope.DESCENDENT);
  FileObject destFileObject = rootNotebookFileObject.resolveFile(
      buildNoteFileName(noteId, newNotePath), NameScope.DESCENDENT);
  // create parent folder first, otherwise move operation will fail
  destFileObject.getParent().createFolder();
  fileObject.moveTo(destFileObject);
}
 
Example #26
Source File: FTPRemoteConnector.java    From datacollector with Apache License 2.0 5 votes vote down vote up
protected FileObject resolveChild(String path) throws IOException {
  // VFS doesn't properly resolve the child if we don't remove the leading slash, even though that's inconsistent
  // with its other methods
  if (path.startsWith("/")) {
    path = path.substring(1);
  }
  return remoteDir.resolveFile(path, NameScope.DESCENDENT);
}
 
Example #27
Source File: VFSNotebookRepo.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Override
public void move(String folderPath, String newFolderPath,
                 AuthenticationInfo subject) throws IOException{
  LOGGER.info("Move folder from " + folderPath + " to " + newFolderPath);
  FileObject fileObject = rootNotebookFileObject.resolveFile(
      folderPath.substring(1), NameScope.DESCENDENT);
  FileObject destFileObject = rootNotebookFileObject.resolveFile(
      newFolderPath.substring(1), NameScope.DESCENDENT);
  // create parent folder first, otherwise move operation will fail
  destFileObject.getParent().createFolder();
  fileObject.moveTo(destFileObject);
}
 
Example #28
Source File: VFSNotebookRepo.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Override
public void remove(String folderPath, AuthenticationInfo subject) throws IOException {
  LOGGER.info("Remove folder: " + folderPath);
  FileObject folderObject = rootNotebookFileObject.resolveFile(
      folderPath.substring(1), NameScope.DESCENDENT);
  folderObject.deleteAll();
}
 
Example #29
Source File: VFSNotebookRepo.java    From zeppelin with Apache License 2.0 5 votes vote down vote up
@Override
public void remove(String noteId, String notePath, AuthenticationInfo subject)
    throws IOException {
  LOGGER.info("Remove note: " + noteId + ", notePath: " + notePath);
  FileObject noteFile = rootNotebookFileObject.resolveFile(
      buildNoteFileName(noteId, notePath), NameScope.DESCENDENT);
  noteFile.delete(Selectors.SELECT_SELF);
}
 
Example #30
Source File: RepositoryVfsFileObject.java    From pentaho-kettle with Apache License 2.0 4 votes vote down vote up
@Override
public FileObject resolveFile( String name, NameScope scope ) throws FileSystemException {
  throw new NotImplementedException();
}