Java Code Examples for java.nio.file.AccessDeniedException

The following examples show how to use java.nio.file.AccessDeniedException. 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 want to check out the right sidebar which shows the related API usage.
Example 1
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 2
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 3
Source Project: dragonwell8_jdk   Source File: FileHelper.java    License: 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 4
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 5
Source Project: buck   Source File: MissingPathsCheckerTest.java    License: 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 6
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 7
Source Project: openjdk-jdk8u   Source File: FileHelper.java    License: 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 8
Source Project: openjdk-jdk9   Source File: BlockDeviceSize.java    License: 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 9
Source Project: jdk8u-jdk   Source File: BlockDeviceSize.java    License: 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 Project: hottub   Source File: BlockDeviceSize.java    License: 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 11
Source Project: genie   Source File: DirectoryManifest.java    License: 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 12
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 13
Source Project: lucene-solr   Source File: TestVirusCheckingFS.java    License: 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 14
Source Project: lucene-solr   Source File: SimpleFSLockFactory.java    License: 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 15
Source Project: lucene-solr   Source File: TestNativeFSLockFactory.java    License: 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 16
Source Project: jdk8u-jdk   Source File: BlockDeviceSize.java    License: 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 Project: jdk8u_jdk   Source File: BlockDeviceSize.java    License: 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 Project: pravega   Source File: FileSystemStorage.java    License: 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 Project: swift-explorer   Source File: SwiftOperationsImpl.java    License: 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 20
Source Project: flink   Source File: LocalFileSystem.java    License: 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 21
Source Project: openhab-core   Source File: WatchQueueReader.java    License: 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 22
@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 23
/**
 * Returns whether the given file may be uploaded.
 *
 * @return Whether the given file may be uploaded.
 */
public void checkUploadAllowed(Path file, boolean checkFileExists) throws IOException {
    if (!isInMusicFolder(file)) {
        throw new AccessDeniedException(file.toString(), null, "Specified location is not in writable music folder");
    }

    if (checkFileExists && Files.exists(file)) {
        throw new FileAlreadyExistsException(file.toString(), null, "File already exists");
    }
}
 
Example 24
Source Project: spring-analysis-note   Source File: PathResourceTests.java    License: MIT License 5 votes vote down vote up
@Test
public void getReadableByteChannelForDir() throws IOException {
	PathResource resource = new PathResource(TEST_DIR);
	try {
		resource.readableChannel();
	}
	catch (AccessDeniedException ex) {
		// on Windows
	}
}
 
Example 25
Source Project: java-tool   Source File: E.java    License: Apache License 2.0 5 votes vote down vote up
public static UnexpectedException ioException(IOException cause, String msg, Object... args) {
    if (cause instanceof AccessDeniedException) {
        throw new org.osgl.exception.AccessDeniedException(cause, msg, args);
    } else if (cause instanceof FileNotFoundException) {
        throw new ResourceNotFoundException(cause, msg, args);
    }
    throw new UnexpectedIOException(cause, msg, args);
}
 
Example 26
Source Project: flink   Source File: BlobServerPutTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Uploads a byte array to a server which cannot create any files via the {@link BlobServer}.
 * File transfers should fail.
 *
 * @param jobId
 * 		job id
 * @param blobType
 * 		whether the BLOB should become permanent or transient
 */
private void testPutBufferFails(@Nullable final JobID jobId, BlobKey.BlobType blobType)
		throws IOException {
	assumeTrue(!OperatingSystem.isWindows()); //setWritable doesn't work on Windows.

	final Configuration config = new Configuration();
	config.setString(BlobServerOptions.STORAGE_DIRECTORY, temporaryFolder.newFolder().getAbsolutePath());

	File tempFileDir = null;
	try (BlobServer server = new BlobServer(config, new VoidBlobStore())) {

		server.start();

		// make sure the blob server cannot create any files in its storage dir
		tempFileDir = server.createTemporaryFilename().getParentFile().getParentFile();
		assertTrue(tempFileDir.setExecutable(true, false));
		assertTrue(tempFileDir.setReadable(true, false));
		assertTrue(tempFileDir.setWritable(false, false));

		byte[] data = new byte[2000000];
		rnd.nextBytes(data);

		// upload the file to the server directly
		exception.expect(AccessDeniedException.class);

		put(server, jobId, data, blobType);

	} finally {
		// set writable again to make sure we can remove the directory
		if (tempFileDir != null) {
			//noinspection ResultOfMethodCallIgnored
			tempFileDir.setWritable(true, false);
		}
	}
}
 
Example 27
Source Project: Flink-CEPplus   Source File: BlobServerPutTest.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Uploads a byte array to a server which cannot create any files via the {@link BlobServer}.
 * File transfers should fail.
 *
 * @param jobId
 * 		job id
 * @param blobType
 * 		whether the BLOB should become permanent or transient
 */
private void testPutBufferFails(@Nullable final JobID jobId, BlobKey.BlobType blobType)
		throws IOException {
	assumeTrue(!OperatingSystem.isWindows()); //setWritable doesn't work on Windows.

	final Configuration config = new Configuration();
	config.setString(BlobServerOptions.STORAGE_DIRECTORY, temporaryFolder.newFolder().getAbsolutePath());

	File tempFileDir = null;
	try (BlobServer server = new BlobServer(config, new VoidBlobStore())) {

		server.start();

		// make sure the blob server cannot create any files in its storage dir
		tempFileDir = server.createTemporaryFilename().getParentFile().getParentFile();
		assertTrue(tempFileDir.setExecutable(true, false));
		assertTrue(tempFileDir.setReadable(true, false));
		assertTrue(tempFileDir.setWritable(false, false));

		byte[] data = new byte[2000000];
		rnd.nextBytes(data);

		// upload the file to the server directly
		exception.expect(AccessDeniedException.class);

		put(server, jobId, data, blobType);

	} finally {
		// set writable again to make sure we can remove the directory
		if (tempFileDir != null) {
			//noinspection ResultOfMethodCallIgnored
			tempFileDir.setWritable(true, false);
		}
	}
}
 
Example 28
Source Project: Chronicle-Queue   Source File: ReadWriteTest.java    License: Apache License 2.0 5 votes vote down vote up
@After
public void teardown() {
    try {
        IOTools.shallowDeleteDirWithFiles(chroniclePath);
    } catch (Exception e) {
        if (e instanceof AccessDeniedException && OS.isWindows())
            System.err.println(e);
        else
            throw e;
    }
}
 
Example 29
Source Project: flink   Source File: FileUtilsTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testDeleteDirectory() throws Exception {

	// deleting a non-existent file should not cause an error

	File doesNotExist = new File(tmp.newFolder(), "abc");
	FileUtils.deleteDirectory(doesNotExist);

	// deleting a write protected file should throw an error

	File cannotDeleteParent = tmp.newFolder();
	File cannotDeleteChild = new File(cannotDeleteParent, "child");

	try {
		assumeTrue(cannotDeleteChild.createNewFile());
		assumeTrue(cannotDeleteParent.setWritable(false));
		assumeTrue(cannotDeleteChild.setWritable(false));

		FileUtils.deleteDirectory(cannotDeleteParent);
		fail("this should fail with an exception");
	}
	catch (AccessDeniedException ignored) {
		// this is expected
	}
	finally {
		//noinspection ResultOfMethodCallIgnored
		cannotDeleteParent.setWritable(true);
		//noinspection ResultOfMethodCallIgnored
		cannotDeleteChild.setWritable(true);
	}
}
 
Example 30
Source Project: ParallelGit   Source File: FilesReadAllBytesTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test(expected = AccessDeniedException.class)
public void readAllBytesFromDirectory_shouldThrowAccessDeniedException() throws IOException {
  initRepository();
  writeToCache("/dir/file.txt", "some text");
  commitToMaster();
  initGitFileSystem();
  GitPath path = gfs.getPath("/dir");
  Files.readAllBytes(path);
}