java.nio.file.AccessDeniedException Java Examples

The following examples show how to use java.nio.file.AccessDeniedException. 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: NotificationsController.java    From pdfsam with GNU Affero General Public License v3.0 6 votes vote down vote up
@EventListener
public void onTaskFailed(TaskExecutionFailedEvent e) {
    if (e.getFailingCause() instanceof InvalidTaskParametersException) {
        container.addNotification(DefaultI18nContext.getInstance().i18n("Invalid parameters"),
                buildLabel(
                        DefaultI18nContext.getInstance()
                                .i18n("Input parameters are invalid, open the application messages for details."),
                        NotificationType.ERROR));
    }
    Throwable root = ExceptionUtils.getRootCause(e.getFailingCause());
    if (root instanceof AccessDeniedException) {
        container.addNotification(DefaultI18nContext.getInstance().i18n("Access denied"),
                buildLabel(DefaultI18nContext.getInstance().i18n(
                        "Unable to access \"{0}\", please make sure you have write permissions or open the application messages for details.",
                        ((AccessDeniedException) root).getFile()), NotificationType.ERROR));
    }
}
 
Example #2
Source File: FileHelper.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static boolean isReadOnlyPath(Path path) throws IOException {
    // Files.isWritable(path) can not really be trusted. At least not on Windows.
    // If path is a directory, we try to create a new file in it.
    if (Files.isDirectory(path)) {
        try {
            Path f = Files.createFile(Paths.get(path.toString(), "dummyFileToCheckReadOnly"));
            System.out.printf("Dir is not read-only, created %s, exists=%b%n", f, Files.exists(f));
            return false;
        } catch (AccessDeniedException e) {
            System.out.printf("'%s' verified read-only by %s%n", path, e.toString());
            return true;
        }
    } else {
        boolean isReadOnly = !Files.isWritable(path);
        System.out.format("isReadOnly '%s': %b%n", path, isReadOnly);
        return isReadOnly;
    }
}
 
Example #3
Source File: BlockDeviceSize.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    try (FileChannel ch = FileChannel.open(BLK_PATH, READ);
         RandomAccessFile file = new RandomAccessFile(BLK_FNAME, "r")) {

        long size1 = ch.size();
        long size2 = file.length();
        if (size1 != size2) {
            throw new RuntimeException("size differs when retrieved" +
                    " in different ways: " + size1 + " != " + size2);
        }
        System.out.println("OK");

    } catch (NoSuchFileException nsfe) {
        System.err.println("File " + BLK_FNAME + " not found." +
                " Skipping test");
    } catch (AccessDeniedException ade) {
        System.err.println("Access to " + BLK_FNAME + " is denied." +
                " Run test as root.");
    }
}
 
Example #4
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 #5
Source File: TestVirusCheckingFS.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
/** Test Files.delete fails if a file has an open inputstream against it */
public void testDeleteSometimesFails() throws IOException {
  Path dir = wrap(createTempDir());

  int counter = 0;
  while (true) {
    Path path = dir.resolve("file" + counter);
    counter++;

    OutputStream file = Files.newOutputStream(path);
    file.write(5);
    file.close();

    // File is now closed, we attempt delete:
    try {
      Files.delete(path);
    } catch (AccessDeniedException ade) {
      // expected (sometimes)
      assertTrue(ade.getMessage().contains("VirusCheckingFS is randomly refusing to delete file "));
      break;
    }

    assertFalse(Files.exists(path));
  }
}
 
Example #6
Source File: SimpleFSLockFactory.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
@Override
protected Lock obtainFSLock(FSDirectory dir, String lockName) throws IOException {
  Path lockDir = dir.getDirectory();
  
  // Ensure that lockDir exists and is a directory.
  // note: this will fail if lockDir is a symlink
  Files.createDirectories(lockDir);
  
  Path lockFile = lockDir.resolve(lockName);
  
  // create the file: this will fail if it already exists
  try {
    Files.createFile(lockFile);
  } catch (FileAlreadyExistsException | AccessDeniedException e) {
    // convert optional specific exception to our optional specific exception
    throw new LockObtainFailedException("Lock held elsewhere: " + lockFile, e);
  }
  
  // used as a best-effort check, to see if the underlying file has changed
  final FileTime creationTime = Files.readAttributes(lockFile, BasicFileAttributes.class).creationTime();
  
  return new SimpleFSLock(lockFile, creationTime);
}
 
Example #7
Source File: BlockDeviceSize.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    try (FileChannel ch = FileChannel.open(BLK_PATH, READ);
         RandomAccessFile file = new RandomAccessFile(BLK_FNAME, "r")) {

        long size1 = ch.size();
        long size2 = file.length();
        if (size1 != size2) {
            throw new RuntimeException("size differs when retrieved" +
                    " in different ways: " + size1 + " != " + size2);
        }
        System.out.println("OK");

    } catch (NoSuchFileException nsfe) {
        System.err.println("File " + BLK_FNAME + " not found." +
                " Skipping test");
    } catch (AccessDeniedException ade) {
        System.err.println("Access to " + BLK_FNAME + " is denied." +
                " Run test as root.");
    }
}
 
Example #8
Source File: MissingPathsCheckerTest.java    From buck with Apache License 2.0 6 votes vote down vote up
@Test
public void testCheckPathsThrowsErrorForNonMissingFileErrors() {
  ProjectFilesystem filesystem =
      new FakeProjectFilesystem(ImmutableSet.of(Paths.get("b"))) {
        @Override
        public <A extends BasicFileAttributes> A readAttributes(
            Path pathRelativeToProjectRoot, Class<A> type, LinkOption... options)
            throws IOException {
          throw new AccessDeniedException("cannot access file");
        }
      };

  thrown.expect(HumanReadableException.class);
  thrown.expectMessage("//:a references inaccessible file or directory 'b'");

  MissingPathsChecker checker = new MissingPathsChecker();
  checker.checkPaths(
      filesystem,
      BuildTargetFactory.newInstance("//:a"),
      ImmutableSet.of(ForwardRelativePath.of("b")));
}
 
Example #9
Source File: BlockDeviceSize.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    try (FileChannel ch = FileChannel.open(BLK_PATH, READ);
         RandomAccessFile file = new RandomAccessFile(BLK_FNAME, "r")) {

        long size1 = ch.size();
        long size2 = file.length();
        if (size1 != size2) {
            throw new RuntimeException("size differs when retrieved" +
                    " in different ways: " + size1 + " != " + size2);
        }
        System.out.println("OK");

    } catch (NoSuchFileException nsfe) {
        System.err.println("File " + BLK_FNAME + " not found." +
                " Skipping test");
    } catch (AccessDeniedException ade) {
        System.err.println("Access to " + BLK_FNAME + " is denied." +
                " Run test as root.");
    }
}
 
Example #10
Source File: FileHelper.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static boolean isReadOnlyPath(Path path) throws IOException {
    // Files.isWritable(path) can not really be trusted. At least not on Windows.
    // If path is a directory, we try to create a new file in it.
    if (Files.isDirectory(path)) {
        try {
            Path f = Files.createFile(Paths.get(path.toString(), "dummyFileToCheckReadOnly"));
            System.out.printf("Dir is not read-only, created %s, exists=%b%n", f, Files.exists(f));
            return false;
        } catch (AccessDeniedException e) {
            System.out.printf("'%s' verified read-only by %s%n", path, e.toString());
            return true;
        }
    } else {
        boolean isReadOnly = !Files.isWritable(path);
        System.out.format("isReadOnly '%s': %b%n", path, isReadOnly);
        return isReadOnly;
    }
}
 
Example #11
Source File: BlockDeviceSize.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    try (FileChannel ch = FileChannel.open(BLK_PATH, READ);
         RandomAccessFile file = new RandomAccessFile(BLK_FNAME, "r")) {

        long size1 = ch.size();
        long size2 = file.length();
        if (size1 != size2) {
            throw new RuntimeException("size differs when retrieved" +
                    " in different ways: " + size1 + " != " + size2);
        }
        System.out.println("OK");

    } catch (NoSuchFileException nsfe) {
        System.err.println("File " + BLK_FNAME + " not found." +
                " Skipping test");
    } catch (AccessDeniedException ade) {
        System.err.println("Access to " + BLK_FNAME + " is denied." +
                " Run test as root.");
    }
}
 
Example #12
Source File: BlockDeviceSize.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    try (FileChannel ch = FileChannel.open(BLK_PATH, READ);
         RandomAccessFile file = new RandomAccessFile(BLK_FNAME, "r")) {

        long size1 = ch.size();
        long size2 = file.length();
        if (size1 != size2) {
            throw new RuntimeException("size differs when retrieved" +
                    " in different ways: " + size1 + " != " + size2);
        }
        System.out.println("OK");

    } catch (NoSuchFileException nsfe) {
        System.err.println("File " + BLK_FNAME + " not found." +
                " Skipping test");
    } catch (AccessDeniedException ade) {
        System.err.println("Access to " + BLK_FNAME + " is denied." +
                " Run test as root.");
    }
}
 
Example #13
Source File: TestNativeFSLockFactory.java    From lucene-solr with Apache License 2.0 6 votes vote down vote up
public void testBadPermissions() throws IOException {
  // create a mock filesystem that will throw exc on creating test.lock
  Path tmpDir = createTempDir();
  tmpDir = FilterPath.unwrap(tmpDir).toRealPath();
  FileSystem mock = new MockBadPermissionsFileSystem(tmpDir.getFileSystem()).getFileSystem(null);
  Path mockPath = mock.getPath(tmpDir.toString());

  // we should get an IOException (typically NoSuchFileException but no guarantee) with
  // our fake AccessDenied added as suppressed.
  Directory dir = getDirectory(mockPath.resolve("indexDir"));
  IOException expected = expectThrows(IOException.class, () -> {
    dir.obtainLock("test.lock");
  });
  AccessDeniedException suppressed = (AccessDeniedException) expected.getSuppressed()[0];
  assertTrue(suppressed.getMessage().contains("fake access denied"));

  dir.close();
}
 
Example #14
Source File: DirectoryManifest.java    From genie with Apache License 2.0 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public FileVisitResult visitFileFailed(final Path file, final IOException ioe) {
    if (ioe instanceof FileSystemLoopException) {
        log.warn("Detected file system cycle visiting while visiting {}. Skipping.", file);
        return FileVisitResult.SKIP_SUBTREE;
    } else if (ioe instanceof AccessDeniedException) {
        log.warn("Access denied for file {}. Skipping", file);
        return FileVisitResult.SKIP_SUBTREE;
    } else if (ioe instanceof NoSuchFileException) {
        log.warn("File or directory disappeared while visiting {}. Skipping", file);
        return FileVisitResult.SKIP_SUBTREE;
    } else {
        log.error("Got unknown error {} while visiting {}. Terminating visitor", ioe.getMessage(), file, ioe);
        // TODO: Not sure if we should do this or skip subtree or just continue and ignore it?
        return FileVisitResult.TERMINATE;
    }
}
 
Example #15
Source File: BlockDeviceSize.java    From jdk8u-jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    try (FileChannel ch = FileChannel.open(BLK_PATH, READ);
         RandomAccessFile file = new RandomAccessFile(BLK_FNAME, "r")) {

        long size1 = ch.size();
        long size2 = file.length();
        if (size1 != size2) {
            throw new RuntimeException("size differs when retrieved" +
                    " in different ways: " + size1 + " != " + size2);
        }
        System.out.println("OK");

    } catch (NoSuchFileException nsfe) {
        System.err.println("File " + BLK_FNAME + " not found." +
                " Skipping test");
    } catch (AccessDeniedException ade) {
        System.err.println("Access to " + BLK_FNAME + " is denied." +
                " Run test as root.");
    }
}
 
Example #16
Source File: BlockDeviceSize.java    From hottub with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    try (FileChannel ch = FileChannel.open(BLK_PATH, READ);
         RandomAccessFile file = new RandomAccessFile(BLK_FNAME, "r")) {

        long size1 = ch.size();
        long size2 = file.length();
        if (size1 != size2) {
            throw new RuntimeException("size differs when retrieved" +
                    " in different ways: " + size1 + " != " + size2);
        }
        System.out.println("OK");

    } catch (NoSuchFileException nsfe) {
        System.err.println("File " + BLK_FNAME + " not found." +
                " Skipping test");
    } catch (AccessDeniedException ade) {
        System.err.println("Access to " + BLK_FNAME + " is denied." +
                " Run test as root.");
    }
}
 
Example #17
Source File: BlockDeviceSize.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Throwable {
    try (FileChannel ch = FileChannel.open(BLK_PATH, READ);
         RandomAccessFile file = new RandomAccessFile(BLK_FNAME, "r")) {

        long size1 = ch.size();
        long size2 = file.length();
        if (size1 != size2) {
            throw new RuntimeException("size differs when retrieved" +
                    " in different ways: " + size1 + " != " + size2);
        }
        System.out.println("OK");

    } catch (NoSuchFileException nsfe) {
        System.err.println("File " + BLK_FNAME + " not found." +
                " Skipping test");
    } catch (AccessDeniedException ade) {
        System.err.println("Access to " + BLK_FNAME + " is denied." +
                " Run test as root.");
    }
}
 
Example #18
Source File: FileSystemStorage.java    From pravega with Apache License 2.0 6 votes vote down vote up
private <T> T throwException(String segmentName, Exception e) throws StreamSegmentException {
    if (e instanceof NoSuchFileException || e instanceof FileNotFoundException) {
        throw new StreamSegmentNotExistsException(segmentName);
    }

    if (e instanceof FileAlreadyExistsException) {
        throw new StreamSegmentExistsException(segmentName);
    }

    if (e instanceof IndexOutOfBoundsException) {
        throw new IllegalArgumentException(e.getMessage());
    }

    if (e instanceof AccessControlException
            || e instanceof AccessDeniedException
            || e instanceof NonWritableChannelException) {
        throw new StreamSegmentSealedException(segmentName, e);
    }

    throw Exceptions.sneakyThrow(e);
}
 
Example #19
Source File: WatchQueueReader.java    From openhab-core with Eclipse Public License 2.0 6 votes vote down vote up
private void registerWithSubDirectories(AbstractWatchService watchService, Path toWatch) throws IOException {
    Files.walkFileTree(toWatch, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
            new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path subDir, BasicFileAttributes attrs)
                        throws IOException {
                    Kind<?>[] kinds = watchService.getWatchEventKinds(subDir);
                    if (kinds != null) {
                        registerDirectoryInternal(watchService, kinds, subDir);
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                    if (exc instanceof AccessDeniedException) {
                        logger.warn("Access to folder '{}' was denied, therefore skipping it.",
                                file.toAbsolutePath().toString());
                    }
                    return FileVisitResult.SKIP_SUBTREE;
                }
            });
}
 
Example #20
Source File: SwiftOperationsImpl.java    From swift-explorer with Apache License 2.0 6 votes vote down vote up
private Queue<Path> getAllFilesPath (Path srcDir, boolean inludeDir) throws IOException
{
	try 
	{
		return FileUtils.getAllFilesPath(srcDir, true) ;
	} 
	catch (IOException e) 
	{
		if (e instanceof AccessDeniedException) {
			StringBuilder msg = new StringBuilder () ;
			msg.append("File Access Denied") ;
			if (((AccessDeniedException)e).getFile() != null) {
				msg.append(": ") ;
				msg.append(((AccessDeniedException)e).getFile()) ;
			}
			throw new CommandException (msg.toString()) ;
		}
		else
			throw e ;
	}
}
 
Example #21
Source File: LocalFileSystem.java    From flink with Apache License 2.0 6 votes vote down vote up
@Override
public boolean rename(final Path src, final Path dst) throws IOException {
	final File srcFile = pathToFile(src);
	final File dstFile = pathToFile(dst);

	final File dstParent = dstFile.getParentFile();

	// Files.move fails if the destination directory doesn't exist
	//noinspection ResultOfMethodCallIgnored -- we don't care if the directory existed or was created
	dstParent.mkdirs();

	try {
		Files.move(srcFile.toPath(), dstFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
		return true;
	}
	catch (NoSuchFileException | AccessDeniedException | DirectoryNotEmptyException | SecurityException ex) {
		// catch the errors that are regular "move failed" exceptions and return false
		return false;
	}
}
 
Example #22
Source File: SFTPFileSystem.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
void checkAccess(SFTPPath path, AccessMode... modes) throws IOException {
    try (Channel channel = channelPool.get()) {
        SftpATTRS attributes = getAttributes(channel, path, true);
        for (AccessMode mode : modes) {
            if (!hasAccess(attributes, mode)) {
                throw new AccessDeniedException(path.path());
            }
        }
    }
}
 
Example #23
Source File: SourceFileVisitor.java    From mojito with Apache License 2.0 5 votes vote down vote up
@Override
public FileVisitResult visitFileFailed(Path file, IOException ioe) throws IOException {
    if (ioe instanceof AccessDeniedException) {
        logger.error(file + ": cannot access directory");
    } else {
        throw ioe;
    }
    return CONTINUE;
}
 
Example #24
Source File: NativeFileAccess.java    From mirror with Apache License 2.0 5 votes vote down vote up
@Override
public void write(Path relative, ByteBuffer data) throws IOException {
  Path path = rootDirectory.resolve(relative);
  mkdir(path.getParent().toAbsolutePath());
  try {
    doWrite(data, path);
  } catch (AccessDeniedException ade) {
    // sometimes code generators mark files as read-only; for now just assume
    // our "newer always wins" logic is correct, and try to write it anyway
    NativeFileAccessUtils.setWritable(path);
    doWrite(data, path);
  }
}
 
Example #25
Source File: GitManagerImpl.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public List<GitBlame> blame(Workspace ws, String path) throws AccessDeniedException, GitAPIException {
    Repository repository = getRepository(ws.getSpaceKey());

    String relativePath = ws.getRelativePath(path).toString();

    try (Git git = Git.wrap(repository)) {
        BlameResult blameResult = git.blame()
                .setFilePath(relativePath)
                .setFollowFileRenames(true)
                .call();

        if (blameResult == null) { // file not exist
            return Lists.newArrayList();
        }

        int lineCnt = blameResult.getResultContents().size();

        return IntStream.range(0, lineCnt)
                .mapToObj(i -> {
                    org.eclipse.jgit.lib.PersonIdent author = blameResult.getSourceAuthor(i);
                    RevCommit commit = blameResult.getSourceCommit(i);

                    GitBlame.GitBlameBuilder builder = GitBlame.builder()
                            .author(mapper.map(author, PersonIdent.class));

                    if (commit != null) {
                        builder.shortName(commit.abbreviate(ABBREVIATION_LENGTH).name());
                    }

                    return builder.build();
                }).collect(Collectors.toList());
    }
}
 
Example #26
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 #27
Source File: MCRFileSystemProvider.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
private void checkFile(MCRFile file, AccessMode... modes) throws AccessDeniedException {
    for (AccessMode mode : modes) {
        switch (mode) {
            case READ:
            case WRITE:
                break;
            case EXECUTE:
                throw new AccessDeniedException(file.toPath().toString(), null, "Unsupported AccessMode: " + mode);
            default:
                throw new UnsupportedOperationException("Unsupported AccessMode: " + mode);
        }
    }
}
 
Example #28
Source File: WorkspaceTest.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testGetPathForAccessDenied() throws AccessDeniedException {
    exception.expect(AccessDeniedException.class);
    exception.expectMessage(is("./.././src"));

    ws.getPath("./.././src");
}
 
Example #29
Source File: TargetFileVisitor.java    From mojito with Apache License 2.0 5 votes vote down vote up
@Override
public FileVisitResult visitFileFailed(Path file, IOException ioe) throws IOException {
    if (ioe instanceof AccessDeniedException) {
        logger.error(file + ": cannot access directory");
    } else {
        throw ioe;
    }
    return CONTINUE;
}
 
Example #30
Source File: WorkspaceTest.java    From WebIDE-Backend with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Test
public void testGetRelativePathPathForAccessDenied() throws AccessDeniedException {
    exception.expect(AccessDeniedException.class);
    exception.expectMessage(is("./.././src"));

    ws.getRelativePath("./.././src");
}