java.nio.file.NotDirectoryException Java Examples

The following examples show how to use java.nio.file.NotDirectoryException. 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: MCRFileSystemProvider.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
static MCRFilesystemNode resolvePath(MCRPath path) throws IOException {
    try {
        String ifsid = nodeCache.getUnchecked(path);
        MCRFilesystemNode node = MCRFilesystemNode.getNode(ifsid);
        if (node != null) {
            return node;
        }
        nodeCache.invalidate(path);
        return resolvePath(path);
    } catch (UncheckedExecutionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof NoSuchFileException) {
            throw (NoSuchFileException) cause;
        }
        if (cause instanceof NotDirectoryException) {
            throw (NotDirectoryException) cause;
        }
        if (cause instanceof IOException) {
            throw (IOException) cause;
        }
        throw e;
    }
}
 
Example #2
Source File: MCRGoogleSitemapCommon.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
/** The constructor 
 * @throws NotDirectoryException */
public MCRGoogleSitemapCommon(File baseDir) throws NotDirectoryException {
    if (!Objects.requireNonNull(baseDir, "baseDir may not be null.").isDirectory()) {
        throw new NotDirectoryException(baseDir.getAbsolutePath());
    }
    this.webappBaseDir = baseDir;
    LOGGER.info("Using webappbaseDir: {}", baseDir.getAbsolutePath());
    objidlist = new ArrayList<>();
    if ((numberOfURLs < 1) || (numberOfURLs > 50000)) {
        numberOfURLs = 50000;
    }
    if (CDIR.length() != 0) {
        File sitemapDirectory = new File(webappBaseDir, CDIR);
        if (!sitemapDirectory.exists()) {
            sitemapDirectory.mkdirs();
        }
    }
}
 
Example #3
Source File: JythonOptionsPanel.java    From zap-extensions with Apache License 2.0 6 votes vote down vote up
@Override
public void validateParam(Object object) throws Exception {
    String modulesPathString = this.modulesPathTextField.getText();
    if (!Strings.isNullOrEmpty(modulesPathString)) {
        File modulesPath = new File(modulesPathString);
        if (!modulesPath.exists()) {
            throw new NoSuchFileException(
                    Constant.messages.getString(
                            "jython.options.error.modulepath.notexist", modulesPath));
        }
        if (!modulesPath.isDirectory()) {
            throw new NotDirectoryException(
                    Constant.messages.getString(
                            "jython.options.error.modulepath.notdirectory", modulesPath));
        }
    }
}
 
Example #4
Source File: SFTPFileSystem.java    From sftp-fs with Apache License 2.0 6 votes vote down vote up
DirectoryStream<Path> newDirectoryStream(final SFTPPath path, Filter<? super Path> filter) throws IOException {
    try (Channel channel = channelPool.get()) {
        List<LsEntry> entries = channel.listFiles(path.path());
        boolean isDirectory = false;
        for (Iterator<LsEntry> i = entries.iterator(); i.hasNext(); ) {
            LsEntry entry = i.next();
            String filename = entry.getFilename();
            if (CURRENT_DIR.equals(filename)) {
                isDirectory = true;
                i.remove();
            } else if (PARENT_DIR.equals(filename)) {
                i.remove();
            }
        }

        if (!isDirectory) {
            // https://github.com/robtimus/sftp-fs/issues/4: don't fail immediately but check the attributes
            // Follow links to ensure the directory attribute can be read correctly
            SftpATTRS attributes = channel.readAttributes(path.path(), true);
            if (!attributes.isDir()) {
                throw new NotDirectoryException(path.path());
            }
        }
        return new SFTPPathDirectoryStream(path, entries, filter);
    }
}
 
Example #5
Source File: JrtFileSystem.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * returns the list of child paths of the given directory "path"
 *
 * @param path name of the directory whose content is listed
 * @return iterator for child paths of the given directory path
 */
Iterator<Path> iteratorOf(JrtPath path, DirectoryStream.Filter<? super Path> filter)
        throws IOException {
    Node node = checkNode(path).resolveLink(true);
    if (!node.isDirectory()) {
        throw new NotDirectoryException(path.getName());
    }
    if (filter == null) {
        return node.getChildren()
                   .stream()
                   .map(child -> (Path)(path.resolve(new JrtPath(this, child.getNameString()).getFileName())))
                   .iterator();
    }
    return node.getChildren()
               .stream()
               .map(child -> (Path)(path.resolve(new JrtPath(this, child.getNameString()).getFileName())))
               .filter(p ->  { try { return filter.accept(p);
                               } catch (IOException x) {}
                               return false;
                              })
               .iterator();
}
 
Example #6
Source File: Security.java    From Elasticsearch with Apache License 2.0 6 votes vote down vote up
/**
 * Ensures configured directory {@code path} exists.
 * @throws IOException if {@code path} exists, but is not a directory, not accessible, or broken symbolic link.
 */
static void ensureDirectoryExists(Path path) throws IOException {
    // this isn't atomic, but neither is createDirectories.
    if (Files.isDirectory(path)) {
        // verify access, following links (throws exception if something is wrong)
        // we only check READ as a sanity test
        path.getFileSystem().provider().checkAccess(path.toRealPath(), AccessMode.READ);
    } else {
        // doesn't exist, or not a directory
        try {
            Files.createDirectories(path);
        } catch (FileAlreadyExistsException e) {
            // convert optional specific exception so the context is clear
            IOException e2 = new NotDirectoryException(path.toString());
            e2.addSuppressed(e);
            throw e2;
        }
    }
}
 
Example #7
Source File: MCRFileSystemProvider.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
private static MCRDirectory getParentDirectory(MCRPath mcrPath) throws IOException {
    if (mcrPath.getNameCount() == 0) {
        throw new IllegalArgumentException("Root component has no parent: " + mcrPath);
    }
    MCRDirectory rootDirectory = MCRFileSystemUtils.getFileCollection(mcrPath.getOwner());
    if (mcrPath.getNameCount() == 1) {
        return rootDirectory;
    }
    MCRPath parentPath = mcrPath.getParent();
    MCRStoredNode parentNode = (MCRStoredNode) rootDirectory
        .getNodeByPath(getAbsolutePathFromRootComponent(parentPath).toString());
    if (parentNode == null) {
        throw new NoSuchFileException(MCRFileSystemUtils.toPath(rootDirectory).toString(),
            getAbsolutePathFromRootComponent(mcrPath).toString(), "Parent directory does not exists.");
    }
    if (parentNode instanceof MCRFile) {
        throw new NotDirectoryException(MCRFileSystemUtils.toPath(parentNode).toString());
    }
    MCRDirectory parentDir = (MCRDirectory) parentNode;
    //warm-up cache
    parentDir.getChildren().close();

    return parentDir;
}
 
Example #8
Source File: JrtFileSystem.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * returns the list of child paths of the given directory "path"
 *
 * @param path name of the directory whose content is listed
 * @return iterator for child paths of the given directory path
 */
Iterator<Path> iteratorOf(JrtPath path, DirectoryStream.Filter<? super Path> filter)
        throws IOException {
    Node node = checkNode(path).resolveLink(true);
    if (!node.isDirectory()) {
        throw new NotDirectoryException(path.getName());
    }
    if (filter == null) {
        return node.getChildren()
                   .stream()
                   .map(child -> (Path)(path.resolve(new JrtPath(this, child.getNameString()).getFileName())))
                   .iterator();
    }
    return node.getChildren()
               .stream()
               .map(child -> (Path)(path.resolve(new JrtPath(this, child.getNameString()).getFileName())))
               .filter(p ->  { try { return filter.accept(p);
                               } catch (IOException x) {}
                               return false;
                              })
               .iterator();
}
 
Example #9
Source File: MCRDirectoryStream.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
private static MCRFile getMCRFile(SecureDirectoryStream ds, Path relativePath) throws IOException {
    MCRStoredNode storedNode = ds.resolve(relativePath);
    if (storedNode != null) {
        throw new FileAlreadyExistsException(ds.dirPath.resolve(relativePath).toString());
    }
    //does not exist, have to create
    MCRStoredNode parent = ds.dir;
    if (relativePath.getNameCount() > 1) {
        parent = (MCRStoredNode) parent.getNodeByPath(relativePath.getParent().toString());
        if (parent == null) {
            throw new NoSuchFileException(ds.dirPath.resolve(relativePath.getParent()).toString());
        }
        if (!(parent instanceof MCRDirectory)) {
            throw new NotDirectoryException(ds.dirPath.resolve(relativePath.getParent()).toString());
        }
    }
    return ((MCRDirectory) parent).createFile(relativePath.getFileName().toString());
}
 
Example #10
Source File: AbstractBuildPackageComputationTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
@Parameters(method = "getAnyPathParams")
public void throwsIfNamedDirectoryIsBrokenSymlink(Kind kind, String targetName)
    throws ExecutionException, InterruptedException, IOException {
  filesystem.createSymLink(Paths.get("symlink"), Paths.get("target-does-not-exist"), false);

  BuildTargetPatternToBuildPackagePathKey key =
      key(CanonicalCellName.rootCell(), kind, "symlink", targetName);

  thrown.expect(ExecutionException.class);
  thrown.expectCause(
      Matchers.anyOf(
          IsInstanceOf.instanceOf(NotDirectoryException.class),
          IsInstanceOf.instanceOf(NoSuchFileException.class)));
  transform("BUCK", key);
}
 
Example #11
Source File: FilePermissions.java    From appengine-plugins-core with Apache License 2.0 6 votes vote down vote up
/**
 * Check whether the current process can create a directory at the specified path. This is useful
 * for providing immediate feedback to an end user that a path they have selected or typed may not
 * be suitable before attempting to create the directory; e.g. in a tooltip.
 *
 * @param path tentative location for directory
 * @throws AccessDeniedException if a directory in the path is not writable
 * @throws NotDirectoryException if a segment of the path is a file
 */
public static void verifyDirectoryCreatable(Path path)
    throws AccessDeniedException, NotDirectoryException {

  Preconditions.checkNotNull(path, "Null directory path");
  for (Path segment = path; segment != null; segment = segment.getParent()) {
    if (Files.exists(segment)) {
      if (Files.isDirectory(segment)) {
        // Can't create a directory if the bottom most currently existing directory in
        // the path is not writable.
        if (!Files.isWritable(segment)) {
          throw new AccessDeniedException(segment + " is not writable");
        }
      } else {
        // Can't create a directory if a non-directory file already exists with that name
        // somewhere in the path.
        throw new NotDirectoryException(segment + " is a file");
      }
      break;
    }
  }
}
 
Example #12
Source File: AbstractBuildPackageComputationTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
@Parameters(method = "getAnyPathParams")
public void throwsIfNamedDirectoryAncestorIsRegularFile(Kind kind, String targetName)
    throws ExecutionException, InterruptedException, IOException {
  filesystem.createNewFile(Paths.get("file"));

  BuildTargetPatternToBuildPackagePathKey key =
      key(CanonicalCellName.rootCell(), kind, "file/dir", targetName);

  thrown.expect(ExecutionException.class);
  thrown.expectCause(
      Matchers.anyOf(
          IsInstanceOf.instanceOf(NoSuchFileException.class),
          IsInstanceOf.instanceOf(NotDirectoryException.class)));
  transform("BUCK", key);
}
 
Example #13
Source File: Version2to3.java    From db with GNU Affero General Public License v3.0 6 votes vote down vote up
/**
 * Gets the number of files in the specified folder. Symbolic links if any are ignored.
 *
 * @param dir
 * @return
 * @throws IOException
 * @throws NotDirectoryException
 */
private int getFilesCount(Path dir) throws IOException, NotDirectoryException {
    int c = 0;
    if (Files.isDirectory(dir)) {
        try (DirectoryStream<Path> files = Files.newDirectoryStream(dir)) {
            for (Path file : files) {
                if (Files.isRegularFile(file) || Files.isSymbolicLink(file)) {
                    // symbolic link also looks like file
                    c++;
                }
            }
        }
    } else {
        throw new NotDirectoryException(dir + " is not directory");
    }

    return c;
}
 
Example #14
Source File: MCRFileSystemProvider.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
private static MCRDirectory getParentDirectory(MCRPath mcrPath) throws NoSuchFileException, NotDirectoryException {
    if (mcrPath.getNameCount() == 0) {
        throw new IllegalArgumentException("Root component has no parent: " + mcrPath);
    }
    MCRDirectory rootDirectory = getRootDirectory(mcrPath);
    if (mcrPath.getNameCount() == 1) {
        return rootDirectory;
    }
    MCRPath parentPath = mcrPath.getParent();
    MCRFilesystemNode parentNode = rootDirectory.getChildByPath(getAbsolutePathFromRootComponent(parentPath)
        .toString());
    if (parentNode == null) {
        throw new NoSuchFileException(rootDirectory.toPath().toString(), getAbsolutePathFromRootComponent(mcrPath)
            .toString(), "Parent directory does not exists.");
    }
    if (parentNode instanceof MCRFile) {
        throw new NotDirectoryException(parentNode.toPath().toString());
    }
    MCRDirectory parentDir = (MCRDirectory) parentNode;
    parentDir.getChildren();//warm-up cache
    return parentDir;
}
 
Example #15
Source File: FilePermissionsTest.java    From appengine-plugins-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testNullDirectory() throws AccessDeniedException, NotDirectoryException {
  try {
    FilePermissions.verifyDirectoryCreatable(null);
    Assert.fail();
  } catch (NullPointerException ex) {
    Assert.assertNotNull(ex.getMessage());
  }
}
 
Example #16
Source File: FilePermissionsTest.java    From appengine-plugins-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testDirectoryCannotBeCreatedDueToPreexistingFile() throws IOException {
  Path file = Files.createTempFile(parent, "prefix", "suffix");
  try {
    FilePermissions.verifyDirectoryCreatable(file);
    Assert.fail("Can create directory over file");
  } catch (NotDirectoryException ex) {
    Assert.assertNotNull(ex.getMessage());
    Assert.assertTrue(ex.getMessage().contains(file.getFileName().toString()));
  }
}
 
Example #17
Source File: FilePermissionsTest.java    From appengine-plugins-core with Apache License 2.0 5 votes vote down vote up
@Test
public void testSubDirectoryCannotBeCreatedDueToPreexistingFile() throws IOException {
  Path file = Files.createTempFile(parent, "prefix", "suffix");
  try {
    FilePermissions.verifyDirectoryCreatable(Paths.get(file.toString(), "bar", "baz"));
    Assert.fail("Can create directory over file");
  } catch (NotDirectoryException ex) {
    Assert.assertNotNull(ex.getMessage());
    Assert.assertTrue(ex.getMessage().contains(file.getFileName().toString()));
  }
}
 
Example #18
Source File: SFTPFileSystemTest.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
@Test
public void testGetDirectoryStreamNotDirectory() throws IOException {
    addFile("/foo");

    NotDirectoryException exception = assertThrows(NotDirectoryException.class,
            () -> fileSystem.newDirectoryStream(createPath("/foo"), AcceptAllFilter.INSTANCE));
    assertEquals("/foo", exception.getFile());
}
 
Example #19
Source File: ZipDirectoryStream.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
ZipDirectoryStream(ZipPath zipPath,
                   DirectoryStream.Filter<? super java.nio.file.Path> filter)
    throws IOException
{
    this.zipfs = zipPath.getFileSystem();
    this.path = zipPath.getResolvedPath();
    this.filter = filter;
    // sanity check
    if (!zipfs.isDirectory(path))
        throw new NotDirectoryException(zipPath.toString());
}
 
Example #20
Source File: ZipDirectoryStream.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
ZipDirectoryStream(ZipPath zipPath,
                   DirectoryStream.Filter<? super java.nio.file.Path> filter)
    throws IOException
{
    this.zipfs = zipPath.getFileSystem();
    this.path = zipPath.getResolvedPath();
    this.filter = filter;
    // sanity check
    if (!zipfs.isDirectory(path))
        throw new NotDirectoryException(zipPath.toString());
}
 
Example #21
Source File: ZipDirectoryStream.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
ZipDirectoryStream(ZipPath zipPath,
                   DirectoryStream.Filter<? super java.nio.file.Path> filter)
    throws IOException
{
    this.zipfs = zipPath.getFileSystem();
    this.path = zipPath.getResolvedPath();
    this.filter = filter;
    // sanity check
    if (!zipfs.isDirectory(path))
        throw new NotDirectoryException(zipPath.toString());
}
 
Example #22
Source File: MakeDirectory.java    From vespa with Apache License 2.0 5 votes vote down vote up
public boolean converge(TaskContext context) {
    boolean systemModified = false;

    Optional<FileAttributes> attributes = attributesCache.forceGet();
    if (attributes.isPresent()) {
        if (!attributes.get().isDirectory()) {
            throw new UncheckedIOException(new NotDirectoryException(path.toString()));
        }
    } else {
        if (createParents) {
            // We'll skip logging system modification here, as we'll log about the creation
            // of the directory next.
            path.createParents();
        }

        context.recordSystemModification(logger, "Creating directory " + path);
        systemModified = true;

        Optional<String> permissions = attributeSync.getPermissions();
        if (permissions.isPresent()) {
            path.createDirectory(permissions.get());
        } else {
            path.createDirectory();
        }
    }

    systemModified |= attributeSync.converge(context, attributesCache);

    return systemModified;
}
 
Example #23
Source File: FilesDirectoryStreamTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test(expected = NotDirectoryException.class)
public void openRegularFile_shouldThrowException() throws IOException {
  initRepository();
  writeToCache("/file.txt");
  commitToMaster();
  initGitFileSystem();
  Files.newDirectoryStream(gfs.getPath("/file.txt"));
}
 
Example #24
Source File: MCRFileSystemProvider.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
@Override
public DirectoryStream<Path> newDirectoryStream(Path dir, Filter<? super Path> filter) throws IOException {
    MCRPath mcrPath = MCRFileSystemUtils.checkPathAbsolute(dir);
    MCRFilesystemNode node = resolvePath(mcrPath);
    if (node instanceof MCRDirectory) {
        return new MCRDirectoryStream((MCRDirectory) node, mcrPath);
    }
    throw new NotDirectoryException(dir.toString());
}
 
Example #25
Source File: Griffin.java    From griffin with Apache License 2.0 5 votes vote down vote up
private void checkPathValidity(Path path, String name) throws FileSystemException, NotDirectoryException, FileAlreadyExistsException {
    if (!Files.isWritable(path)) {
        System.out.println("That path doesn't seem to be writable :(" + LINE_SEPARATOR + "Check if you have write permission to that path and try again.");
        throw new java.nio.file.FileSystemException(path.toString());
    }
    if (Files.exists(path.resolve(name))) {
        System.out.println("Aw shucks! It seems like there is already a file of that name at that path :(" + LINE_SEPARATOR + "Try again with another name.");
        throw new FileAlreadyExistsException(path.resolve(name).toString());
    }
    if (!Files.isDirectory(path)) {
        System.out.println("Aw, man. That path does not seem to be a valid directory :(" + LINE_SEPARATOR + "Try with another path again.");
        throw new java.nio.file.NotDirectoryException(path.toString());
    }
}
 
Example #26
Source File: ZipDirectoryStream.java    From jdk8u-dev-jdk with GNU General Public License v2.0 5 votes vote down vote up
ZipDirectoryStream(ZipPath zipPath,
                   DirectoryStream.Filter<? super java.nio.file.Path> filter)
    throws IOException
{
    this.zipfs = zipPath.getFileSystem();
    this.path = zipPath.getResolvedPath();
    this.filter = filter;
    // sanity check
    if (!zipfs.isDirectory(path))
        throw new NotDirectoryException(zipPath.toString());
}
 
Example #27
Source File: FilesDirectoryStreamTest.java    From ParallelGit with Apache License 2.0 5 votes vote down vote up
@Test(expected = NotDirectoryException.class)
public void openRegularFile_shouldThrowException() throws IOException {
  initRepository();
  writeToCache("/file.txt");
  commitToMaster();
  initGitFileSystem();
  Files.newDirectoryStream(gfs.getPath("/file.txt"));
}
 
Example #28
Source File: UnixSshPath.java    From jsch-nio with MIT License 5 votes vote down vote up
/** {@inheritDoc} */
@Override
public WatchKey register( WatchService watcher, Kind<?>[] events, Modifier... modifiers ) throws IOException {
    if ( watcher == null ) {
        throw new NullPointerException();
    }
    if ( !(watcher instanceof UnixSshFileSystemWatchService) ) {
        throw new ProviderMismatchException();
    }
    if ( !getFileSystem().provider().readAttributes( this, BasicFileAttributes.class ).isDirectory() ) {
        throw new NotDirectoryException( this.toString() );
    }
    getFileSystem().provider().checkAccess( this, AccessMode.READ );
    return ((UnixSshFileSystemWatchService) watcher).register( this, events, modifiers );
}
 
Example #29
Source File: XcodeToolFinder.java    From buck with Apache License 2.0 5 votes vote down vote up
@Override
public ImmutableSet<Path> load(@Nonnull Path key) throws IOException {
  try (Stream<Path> contents = Files.list(key)) {
    return RichStream.from(contents).map(Path::getFileName).toImmutableSet();
  } catch (NotDirectoryException | NoSuchFileException e) {
    return ImmutableSet.of();
  }
}
 
Example #30
Source File: WatchmanBuildPackageComputation.java    From buck with Apache License 2.0 5 votes vote down vote up
/** @throws NotDirectoryException {@code basePath} does not exist or is not a directory. */
private void validateBasePath(Path basePath, Exception cause) throws IOException {
  if (!filesystemView.isDirectory(basePath)) {
    IOException e = new NotDirectoryException(basePath.toString());
    e.initCause(cause);
    throw e;
  }
}