下面列出了java.nio.file.AccessMode#java.nio.file.AccessDeniedException 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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.");
}
}
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.");
}
}
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;
}
}
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.");
}
}
@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")));
}
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.");
}
}
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;
}
}
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.");
}
}
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.");
}
}
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.");
}
}
/**
* {@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;
}
}
/**
* 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;
}
}
}
/** 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));
}
}
@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);
}
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();
}
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.");
}
}
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.");
}
}
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);
}
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 ;
}
}
@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;
}
}
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;
}
});
}
@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));
}
}
/**
* 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");
}
}
@Test
public void getReadableByteChannelForDir() throws IOException {
PathResource resource = new PathResource(TEST_DIR);
try {
resource.readableChannel();
}
catch (AccessDeniedException ex) {
// on Windows
}
}
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);
}
/**
* 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);
}
}
}
/**
* 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);
}
}
}
@After
public void teardown() {
try {
IOTools.shallowDeleteDirWithFiles(chroniclePath);
} catch (Exception e) {
if (e instanceof AccessDeniedException && OS.isWindows())
System.err.println(e);
else
throw e;
}
}
@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);
}
}
@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);
}