Java Code Examples for java.nio.file.NotDirectoryException

The following examples show how to use java.nio.file.NotDirectoryException. 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: db   Source File: Version2to3.java    License: 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 2
Source Project: Bytecoder   Source File: JrtFileSystem.java    License: 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 3
Source Project: Elasticsearch   Source File: Security.java    License: 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 4
Source Project: openjdk-jdk9   Source File: JrtFileSystem.java    License: 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 5
/** 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 6
Source Project: mycore   Source File: MCRFileSystemProvider.java    License: 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 7
Source Project: mycore   Source File: MCRDirectoryStream.java    License: 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 8
Source Project: mycore   Source File: MCRFileSystemProvider.java    License: 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 9
Source Project: mycore   Source File: MCRFileSystemProvider.java    License: 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 10
Source Project: appengine-plugins-core   Source File: FilePermissions.java    License: 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 11
Source Project: sftp-fs   Source File: SFTPFileSystem.java    License: 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 12
Source Project: zap-extensions   Source File: JythonOptionsPanel.java    License: 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 13
Source Project: buck   Source File: AbstractBuildPackageComputationTest.java    License: 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 14
Source Project: buck   Source File: AbstractBuildPackageComputationTest.java    License: 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 15
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 16
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 17
Source Project: jdk8u60   Source File: ZipDirectoryStream.java    License: 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 18
Source Project: bundletool   Source File: SdkToolsLocator.java    License: Apache License 2.0 5 votes vote down vote up
private Optional<Path> locateBinaryOnSystemPath(
    String binaryGlob, SystemEnvironmentProvider systemEnvironmentProvider) {

  Optional<String> rawPath = systemEnvironmentProvider.getVariable(SYSTEM_PATH_VARIABLE);
  if (!rawPath.isPresent()) {
    return Optional.empty();
  }

  // Any sane Java runtime should define this property.
  String pathSeparator = systemEnvironmentProvider.getProperty("path.separator").get();

  PathMatcher binPathMatcher = fileSystem.getPathMatcher(binaryGlob);
  for (String pathDir : Splitter.on(pathSeparator).splitToList(rawPath.get())) {
    try (Stream<Path> pathStream =
        Files.find(
            fileSystem.getPath(pathDir),
            /* maxDepth= */ 1,
            (path, attributes) ->
                binPathMatcher.matches(path)
                    && Files.isExecutable(path)
                    && Files.isRegularFile(path))) {

      Optional<Path> binaryInDir = pathStream.findFirst();
      if (binaryInDir.isPresent()) {
        return binaryInDir;
      }
    } catch (NoSuchFileException | NotDirectoryException | InvalidPathException tolerate) {
      // Tolerate invalid PATH entries.
    } catch (IOException e) {
      throw CommandExecutionException.builder()
          .withCause(e)
          .withInternalMessage(
              "Error while trying to locate adb on system PATH in directory '%s'.", pathDir)
          .build();
    }
  }

  return Optional.empty();
}
 
Example 19
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 Project: jobson   Source File: FilesystemJobSpecDAO.java    License: Apache License 2.0 5 votes vote down vote up
public FilesystemJobSpecDAO(Path jobSpecsDir) throws IOException {
    requireNonNull(jobSpecsDir);
    if (!jobSpecsDir.toFile().exists())
        throw new FileNotFoundException(jobSpecsDir.toString() + ": No such directory");
    if (!jobSpecsDir.toFile().isDirectory())
        throw new NotDirectoryException(jobSpecsDir.toString() + ": Is not a directory");

    this.jobSpecsDir = jobSpecsDir;
}
 
Example 21
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 Project: Bytecoder   Source File: JrtDirectoryStream.java    License: Apache License 2.0 5 votes vote down vote up
JrtDirectoryStream(JrtPath dir,
        DirectoryStream.Filter<? super java.nio.file.Path> filter)
        throws IOException
{
    this.dir = dir;
    if (!dir.jrtfs.isDirectory(dir, true)) {  // sanity check
        throw new NotDirectoryException(dir.toString());
    }
    this.filter = filter;
}
 
Example 23
Source Project: Bytecoder   Source File: PollingWatchService.java    License: Apache License 2.0 5 votes vote down vote up
private PollingWatchKey doPrivilegedRegister(Path path,
                                             Set<? extends WatchEvent.Kind<?>> events,
                                             int sensitivityInSeconds)
    throws IOException
{
    // check file is a directory and get its file key if possible
    BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
    if (!attrs.isDirectory()) {
        throw new NotDirectoryException(path.toString());
    }
    Object fileKey = attrs.fileKey();
    if (fileKey == null)
        throw new AssertionError("File keys must be supported");

    // grab close lock to ensure that watch service cannot be closed
    synchronized (closeLock()) {
        if (!isOpen())
            throw new ClosedWatchServiceException();

        PollingWatchKey watchKey;
        synchronized (map) {
            watchKey = map.get(fileKey);
            if (watchKey == null) {
                // new registration
                watchKey = new PollingWatchKey(path, this, fileKey);
                map.put(fileKey, watchKey);
            } else {
                // update to existing registration
                watchKey.disable();
            }
        }
        watchKey.enable(events, sensitivityInSeconds);
        return watchKey;
    }

}
 
Example 24
JrtDirectoryStream(JrtPath dir,
        DirectoryStream.Filter<? super java.nio.file.Path> filter)
        throws IOException
{
    this.dir = dir;
    if (!dir.jrtfs.isDirectory(dir, true)) {  // sanity check
        throw new NotDirectoryException(dir.toString());
    }
    this.filter = filter;
}
 
Example 25
private PollingWatchKey doPrivilegedRegister(Path path,
                                             Set<? extends WatchEvent.Kind<?>> events,
                                             int sensitivityInSeconds)
    throws IOException
{
    // check file is a directory and get its file key if possible
    BasicFileAttributes attrs = Files.readAttributes(path, BasicFileAttributes.class);
    if (!attrs.isDirectory()) {
        throw new NotDirectoryException(path.toString());
    }
    Object fileKey = attrs.fileKey();
    if (fileKey == null)
        throw new AssertionError("File keys must be supported");

    // grab close lock to ensure that watch service cannot be closed
    synchronized (closeLock()) {
        if (!isOpen())
            throw new ClosedWatchServiceException();

        PollingWatchKey watchKey;
        synchronized (map) {
            watchKey = map.get(fileKey);
            if (watchKey == null) {
                // new registration
                watchKey = new PollingWatchKey(path, this, fileKey);
                map.put(fileKey, watchKey);
            } else {
                // update to existing registration
                watchKey.disable();
            }
        }
        watchKey.enable(events, sensitivityInSeconds);
        return watchKey;
    }

}
 
Example 26
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 Project: jdk8u-jdk   Source File: ZipDirectoryStream.java    License: 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 28
Source Project: hottub   Source File: ZipDirectoryStream.java    License: 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 29
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 30
private void checkTempStoragePath(String location) throws IOException {
    Path targetDir = Paths.get(location);
    if (!targetDir.isAbsolute()) {
        throw new MCRConfigurationException(
            "'" + MCR_FILE_UPLOAD_TEMP_STORAGE_PATH + "=" + location + "' must be an absolute path!");
    }
    if (Files.notExists(targetDir)) {
        LogManager.getLogger().info("Creating directory: {}", targetDir);
        Files.createDirectories(targetDir);
    }
    if (!Files.isDirectory(targetDir)) {
        throw new NotDirectoryException(targetDir.toString());
    }
}