java.nio.file.FileSystemException Java Examples

The following examples show how to use java.nio.file.FileSystemException. 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: FileUtilsTest.java    From flink with Apache License 2.0 6 votes vote down vote up
/**
 * Deleting a symbolic link directory should not delete the files in it.
 */
@Test
public void testDeleteSymbolicLinkDirectory() throws Exception {
	// creating a directory to which the test creates a symbolic link
	File linkedDirectory = tmp.newFolder();
	File fileInLinkedDirectory = new File(linkedDirectory, "child");
	assertTrue(fileInLinkedDirectory.createNewFile());

	File symbolicLink = new File(tmp.getRoot(), "symLink");
	try {
		Files.createSymbolicLink(symbolicLink.toPath(), linkedDirectory.toPath());
	} catch (FileSystemException e) {
		// this operation can fail under Windows due to: "A required privilege is not held by the client."
		assumeFalse("This test does not work properly under Windows", OperatingSystem.isWindows());
		throw e;
	}

	FileUtils.deleteDirectory(symbolicLink);
	assertTrue(fileInLinkedDirectory.exists());
}
 
Example #2
Source File: SymLinkTest.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
void test(Path base, String name) throws IOException {
    Path file = base.resolve(name);
    Path javaFile = base.resolve("HelloWorld.java");
    tb.writeFile(file,
            "public class HelloWorld {\n"
            + "    public static void main(String... args) {\n"
            + "        System.err.println(\"Hello World!\");\n"
            + "    }\n"
            + "}");

    try {
        Files.createSymbolicLink(javaFile, file.getFileName());
    } catch (FileSystemException fse) {
        System.err.println("warning: test passes vacuously, sym-link could not be created");
        System.err.println(fse.getMessage());
        return;
    }

    Path classes = Files.createDirectories(base.resolve("classes"));
    new JavacTask(tb)
        .outdir(classes)
        .files(javaFile)
        .run()
        .writeAll();
}
 
Example #3
Source File: Log4j1ConfigurationFactoryTest.java    From logging-log4j2 with Apache License 2.0 6 votes vote down vote up
@Test
public void testSystemProperties1() throws Exception {
       final String tempFileName = System.getProperty("java.io.tmpdir") + "/hadoop.log";
       final Path tempFilePath = new File(tempFileName).toPath();
       Files.deleteIfExists(tempFilePath);
       try {
           final Configuration configuration = getConfiguration("config-1.2/log4j-system-properties-1.properties");
           final RollingFileAppender appender = configuration.getAppender("RFA");
		appender.stop(10, TimeUnit.SECONDS);
           System.out.println("expected: " + tempFileName + " Actual: " + appender.getFileName());
           assertEquals(tempFileName, appender.getFileName());
       } finally {
		try {
			Files.deleteIfExists(tempFilePath);
		} catch (final FileSystemException e) {
			e.printStackTrace();
		}
       }
}
 
Example #4
Source File: SinkFile.java    From geoportal-server-harvester with Apache License 2.0 6 votes vote down vote up
/**
 * Attempts to delete file
 * @param attempts number of attempts
 * @param mills delay between consecutive attempts
 * @throws IOException if all attempts fail
 */
private void attemptToDeleteFile(int attempts, long mills) throws IOException {
  while (true) {
    attempts--;
    try {
      Files.delete(file);
      return;
    } catch (FileSystemException ex) {
      // if not check if maximum number of attempts has been exhausted...
      if (attempts <= 0) {
        // ...then throw exceptiion
        throw ex;
      }
      // otherwise wait and try again latter
      try {
        Thread.sleep(mills);
      } catch (InterruptedException e) {
        // ignore
      }
    }
  }
}
 
Example #5
Source File: SFTPFileSystemTest.java    From sftp-fs with Apache License 2.0 6 votes vote down vote up
@Test
public void testMoveReplaceFile() throws IOException {
    addDirectory("/foo");
    addDirectory("/foo/bar");
    addFile("/baz");

    CopyOption[] options = {};
    FileSystemException exception = assertThrows(FileSystemException.class,
            () -> fileSystem.move(createPath("/baz"), createPath("/foo/bar"), options));
    assertEquals("/baz", exception.getFile());
    assertEquals("/foo/bar", exception.getOtherFile());

    verify(getExceptionFactory()).createMoveException(eq("/baz"), eq("/foo/bar"), any(SftpException.class));
    assertTrue(Files.isDirectory(getPath("/foo")));
    assertTrue(Files.isDirectory(getPath("/foo/bar")));
    assertTrue(Files.isRegularFile(getPath("/baz")));
}
 
Example #6
Source File: SFTPFileSystemTest.java    From sftp-fs with Apache License 2.0 6 votes vote down vote up
@Test
public void testMoveSFTPFailure() throws IOException {
    addDirectory("/foo");
    addFile("/foo/bar");

    // failure: non-existing target parent

    CopyOption[] options = {};
    FileSystemException exception = assertThrows(FileSystemException.class,
            () -> fileSystem.move(createPath("/foo/bar"), createPath("/baz/bar"), options));
    assertEquals("/foo/bar", exception.getFile());
    assertEquals("/baz/bar", exception.getOtherFile());

    verify(getExceptionFactory()).createMoveException(eq("/foo/bar"), eq("/baz/bar"), any(SftpException.class));
    assertTrue(Files.isDirectory(getPath("/foo")));
    assertTrue(Files.isRegularFile(getPath("/foo/bar")));
    assertFalse(Files.exists(getPath("/baz")));
}
 
Example #7
Source File: SFTPFileSystemTest.java    From sftp-fs with Apache License 2.0 6 votes vote down vote up
@Test
public void testCopyReplaceNonEmptyDirAllowedDifferentFileSystems() throws IOException {
    addDirectory("/foo");
    addFile("/foo/bar");
    addFile("/baz");

    CopyOption[] options = { StandardCopyOption.REPLACE_EXISTING };
    FileSystemException exception = assertThrows(FileSystemException.class,
            () -> fileSystem.copy(createPath("/baz"), createPath(fileSystem2, "/foo"), options));
    assertEquals("/foo", exception.getFile());

    verify(getExceptionFactory()).createDeleteException(eq("/foo"), any(SftpException.class), eq(true));
    assertTrue(Files.isDirectory(getPath("/foo")));
    assertTrue(Files.isRegularFile(getPath("/foo/bar")));
    assertTrue(Files.isRegularFile(getPath("/baz")));
}
 
Example #8
Source File: SFTPFileSystemTest.java    From sftp-fs with Apache License 2.0 6 votes vote down vote up
@Test
public void testCopyReplaceNonEmptyDirAllowed() throws IOException {
    addDirectory("/foo");
    addFile("/foo/bar");
    addFile("/baz");

    CopyOption[] options = { StandardCopyOption.REPLACE_EXISTING };
    FileSystemException exception = assertThrows(FileSystemException.class,
            () -> fileSystem.copy(createPath("/baz"), createPath("/foo"), options));
    assertEquals("/foo", exception.getFile());

    verify(getExceptionFactory()).createDeleteException(eq("/foo"), any(SftpException.class), eq(true));
    assertTrue(Files.isDirectory(getPath("/foo")));
    assertTrue(Files.isRegularFile(getPath("/foo/bar")));
    assertTrue(Files.isRegularFile(getPath("/baz")));
}
 
Example #9
Source File: MCRIFSFileSystem.java    From mycore with GNU General Public License v3.0 6 votes vote down vote up
@Override
public void removeRoot(String owner) throws FileSystemException {
    MCRPath rootPath = getPath(owner, "", this);
    MCRDirectory rootDirectory = MCRDirectory.getRootDirectory(owner);
    if (rootDirectory == null) {
        throw new NoSuchFileException(rootPath.toString());
    }
    if (rootDirectory.isDeleted()) {
        return;
    }
    if (rootDirectory.hasChildren()) {
        throw new DirectoryNotEmptyException(rootPath.toString());
    }
    try {
        rootDirectory.delete();
    } catch (RuntimeException e) {
        LogManager.getLogger(getClass()).warn("Catched run time exception while removing root directory.", e);
        throw new FileSystemException(rootPath.toString(), null, e.getMessage());
    }
    LogManager.getLogger(getClass()).info("Removed root directory: {}", rootPath);
}
 
Example #10
Source File: SFTPFileSystemTest.java    From sftp-fs with Apache License 2.0 6 votes vote down vote up
@Test
public void testNewOutputStreamExistingSFTPFailure() throws IOException {
    addDirectory("/foo");
    Path bar = addFile("/foo/bar");
    bar.toFile().setReadOnly();

    // failure: no permission to write

    OpenOption[] options = { StandardOpenOption.WRITE };
    FileSystemException exception = assertThrows(FileSystemException.class, () -> fileSystem.newOutputStream(createPath("/foo/bar"), options));
    assertEquals("/foo/bar", exception.getFile());

    verify(getExceptionFactory()).createNewOutputStreamException(eq("/foo/bar"), any(SftpException.class), anyCollection());
    assertTrue(Files.isDirectory(getPath("/foo")));
    assertTrue(Files.isRegularFile(getPath("/foo/bar")));
}
 
Example #11
Source File: FileSystemView.java    From jimfs with Apache License 2.0 6 votes vote down vote up
/** Checks that the given file can be deleted, throwing an exception if it can't. */
private void checkDeletable(File file, DeleteMode mode, Path path) throws IOException {
  if (file.isRootDirectory()) {
    throw new FileSystemException(path.toString(), null, "can't delete root directory");
  }

  if (file.isDirectory()) {
    if (mode == DeleteMode.NON_DIRECTORY_ONLY) {
      throw new FileSystemException(path.toString(), null, "can't delete: is a directory");
    }

    checkEmpty(((Directory) file), path);
  } else if (mode == DeleteMode.DIRECTORY_ONLY) {
    throw new FileSystemException(path.toString(), null, "can't delete: is not a directory");
  }

  if (file == workingDirectory && !path.isAbsolute()) {
    // this is weird, but on Unix at least, the file system seems to be happy to delete the
    // working directory if you give the absolute path to it but fail if you use a relative path
    // that resolves to the working directory (e.g. "" or ".")
    throw new FileSystemException(path.toString(), null, "invalid argument");
  }
}
 
Example #12
Source File: SFTPFileSystemTest.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeleteSFTPFailure() throws IOException {
    addDirectory("/foo/bar/baz");

    // failure: non-empty directory

    FileSystemException exception = assertThrows(FileSystemException.class, () -> fileSystem.delete(createPath("/foo/bar")));
    assertEquals("/foo/bar", exception.getFile());

    verify(getExceptionFactory()).createDeleteException(eq("/foo/bar"), any(SftpException.class), eq(true));
    assertTrue(Files.isDirectory(getPath("/foo")));
    assertTrue(Files.isDirectory(getPath("/foo/bar")));
    assertTrue(Files.isDirectory(getPath("/foo/bar/baz")));
}
 
Example #13
Source File: SFTPFileSystemTest.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
@Test
public void testMoveReplaceEmptyDir() throws IOException {
    addDirectory("/foo");
    addFile("/baz");

    CopyOption[] options = {};
    FileSystemException exception = assertThrows(FileSystemException.class,
            () -> fileSystem.move(createPath("/baz"), createPath("/foo"), options));
    assertEquals("/baz", exception.getFile());
    assertEquals("/foo", exception.getOtherFile());

    verify(getExceptionFactory()).createMoveException(eq("/baz"), eq("/foo"), any(SftpException.class));
    assertTrue(Files.isDirectory(getPath("/foo")));
    assertTrue(Files.isRegularFile(getPath("/baz")));
}
 
Example #14
Source File: SFTPFileSystemTest.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
@Test
public void testNewOutputStreamDirectoryDeleteOnClose() throws IOException {
    addDirectory("/foo");

    OpenOption[] options = { StandardOpenOption.DELETE_ON_CLOSE };
    FileSystemException exception = assertThrows(FileSystemException.class, () -> fileSystem.newOutputStream(createPath("/foo"), options));
    assertEquals("/foo", exception.getFile());
    assertEquals(Messages.fileSystemProvider().isDirectory("/foo").getReason(), exception.getReason());

    verify(getExceptionFactory(), never()).createNewOutputStreamException(anyString(), any(SftpException.class), anyCollection());
    assertTrue(Files.isDirectory(getPath("/foo")));
    assertEquals(0, getChildCount("/foo"));
}
 
Example #15
Source File: SFTPFileSystemTest.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
@Test
public void testReadSymbolicLinkNoLinkButFile() throws IOException {
    addFile("/foo");

    FileSystemException exception = assertThrows(FileSystemException.class, () -> fileSystem.readSymbolicLink(createPath("/foo")));
    assertEquals("/foo", exception.getFile());

    verify(getExceptionFactory()).createReadLinkException(eq("/foo"), any(SftpException.class));
}
 
Example #16
Source File: JimfsWindowsLikeFileSystemTest.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@Test
public void testDelete_directory_cantDeleteRoot() throws IOException {
  // test with E:\ because it is empty
  try {
    Files.delete(path("E:\\"));
    fail();
  } catch (FileSystemException expected) {
    assertThat(expected.getFile()).isEqualTo("E:\\");
    assertThat(expected.getMessage()).contains("root");
  }
}
 
Example #17
Source File: SFTPFileSystemTest.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetGroupNonExisting() {
    FileSystemException exception = assertThrows(FileSystemException.class,
            () -> fileSystem.setGroup(createPath("/foo/bar"), new SimpleGroupPrincipal("1")));
    assertEquals("/foo/bar", exception.getFile());

    verify(getExceptionFactory()).createSetGroupException(eq("/foo/bar"), any(SftpException.class));
}
 
Example #18
Source File: SFTPFileSystemTest.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
@Test
public void testSetOwnerNonExisting() {
    FileSystemException exception = assertThrows(FileSystemException.class,
            () -> fileSystem.setOwner(createPath("/foo/bar"), new SimpleUserPrincipal("1")));
    assertEquals("/foo/bar", exception.getFile());

    verify(getExceptionFactory()).createSetOwnerException(eq("/foo/bar"), any(SftpException.class));
}
 
Example #19
Source File: DefaultFileLockManagerTimeoutTest.java    From archiva with Apache License 2.0 5 votes vote down vote up
@Test(expected = FileLockTimeoutException.class)
public void testTimeout()
    throws Throwable
{

        try {
            Path file = Paths.get(System.getProperty("buildDirectory"), "foo.txt");

            Files.deleteIfExists(file);

            Path largeJar = Paths.get(System.getProperty("basedir"), "src/test/cassandra-all-2.0.3.jar");

            Lock lock = fileLockManager.writeFileLock(file);

            try {
                Files.copy(largeJar, lock.getFile(), StandardCopyOption.REPLACE_EXISTING);
            } catch (IOException e) {
                logger.warn("Copy failed {}", e.getMessage());
                // On windows a FileSystemException is thrown
                // We ignore this
            }

            lock = fileLockManager.writeFileLock(file);
        } catch (FileSystemException ex) {
            logger.error("Exception from filesystem {}", ex.getMessage());
            ex.printStackTrace();
            throw ex;
        }

}
 
Example #20
Source File: FileBlobStoreIT.java    From nexus-public with Eclipse Public License 1.0 5 votes vote down vote up
@Test
public void blobMoveRetriesOnFileSystemException() throws Exception {
  byte[] content = testData();
  HashCode sha1 = Hashing.sha1().hashBytes(content);
  Path sourceFile = testFile(content);

  doThrow(new FileSystemException("The process cannot access the file because it is being used by another process."))
      .when(fileOperations).moveAtomic(any(), any());

  underTest.create(sourceFile, TEST_HEADERS, content.length, sha1);

  verify(fileOperations, times(2)).copy(any(), any());
  verify(fileOperations, times(2)).delete(any());
}
 
Example #21
Source File: SFTPFileSystemTest.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
@Test
public void testNewOutputStreamDirectoryNoCreate() throws IOException {
    addDirectory("/foo");

    OpenOption[] options = { StandardOpenOption.WRITE };
    FileSystemException exception = assertThrows(FileSystemException.class, () -> fileSystem.newOutputStream(createPath("/foo"), options));
    assertEquals("/foo", exception.getFile());
    assertEquals(Messages.fileSystemProvider().isDirectory("/foo").getReason(), exception.getReason());

    verify(getExceptionFactory(), never()).createNewOutputStreamException(anyString(), any(SftpException.class), anyCollection());
    assertTrue(Files.isDirectory(getPath("/foo")));
    assertEquals(0, getChildCount("/foo"));
}
 
Example #22
Source File: WatchmanBuildPackageComputation.java    From buck with Apache License 2.0 5 votes vote down vote up
private boolean isNotADirectoryError(FileSystemException exception) {
  String reason = exception.getReason();
  if (reason == null) {
    return false;
  }
  String posixMessage = "Not a directory";
  String windowsMessage = "The directory name is invalid";
  return reason.equals(posixMessage) || reason.contains(windowsMessage);
}
 
Example #23
Source File: Griffin.java    From griffin with Apache License 2.0 5 votes vote down vote up
private void checkPathValidity(Path path, String name) throws FileSystemException, NotDirectoryException, FileAlreadyExistsException {
    if (!Files.isWritable(path)) {
        System.out.println("That path doesn't seem to be writable :(" + LINE_SEPARATOR + "Check if you have write permission to that path and try again.");
        throw new java.nio.file.FileSystemException(path.toString());
    }
    if (Files.exists(path.resolve(name))) {
        System.out.println("Aw shucks! It seems like there is already a file of that name at that path :(" + LINE_SEPARATOR + "Try again with another name.");
        throw new FileAlreadyExistsException(path.resolve(name).toString());
    }
    if (!Files.isDirectory(path)) {
        System.out.println("Aw, man. That path does not seem to be a valid directory :(" + LINE_SEPARATOR + "Try with another path again.");
        throw new java.nio.file.NotDirectoryException(path.toString());
    }
}
 
Example #24
Source File: WatchmanBuildPackageComputation.java    From buck with Apache License 2.0 5 votes vote down vote up
private FileSystemException enrichFileSystemException(FileSystemException exception) {
  if (!(exception instanceof NotDirectoryException) && isNotADirectoryError(exception)) {
    FileSystemException e = new NotDirectoryException(exception.getFile());
    e.initCause(exception);
    return e;
  }
  return exception;
}
 
Example #25
Source File: Warning.java    From update4j with Apache License 2.0 5 votes vote down vote up
public static void lock(Throwable t) {
    if (!(t instanceof FileSystemException))
        return;

    FileSystemException fse = (FileSystemException) t;
    String msg = t.getMessage();
    if (!msg.contains("another process") && !msg.contains("lock") && !msg.contains("use")) {
        return;
    }

    if (!shouldWarn("lock"))
        return;

    logger.log(WARNING, fse.getFile()
                    + "' is locked by another process, there are a few common causes for this:\n"
                    + "\t- Another application accesses this file:\n"
                    + "\t\tNothing you can do about it, it's out of your control.\n"
                    + "\t- 2 instances of this application run simultaneously:\n"
                    + "\t\tUse SingleInstanceManager to restrict running more than one instance.\n"
                    + "\t- You are calling update() after launch() and files are already loaded onto JVM:\n"
                    + "\t\tUse updateTemp() instead. Call Update.finalizeUpdate() upon next restart\n"
                    + "\t\tto complete the update process.\n"
                    + "\t- You are attempting to update a file that runs in the bootstrap application:\n"
                    + "\t\tBootstrap dependencies cannot typically be updated. For services, leave\n"
                    + "\t\tthe old in place, just release a newer version with a higher version\n"
                    + "\t\tnumber and make it available to the boot classpath or modulepath.\n"
                    + "\t- A file that's required in the business application was added to the boot classpath or modulepath:\n"
                    + "\t\tMuch care must be taken that business application files should NOT be\n"
                    + "\t\tloaded in the boot, the JVM locks them and prevents them from being updated.\n");
}
 
Example #26
Source File: SSHChannelPool.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
IOException asIOException(Exception e) throws IOException {
    if (e instanceof IOException) {
        throw (IOException) e;
    }
    FileSystemException exception = new FileSystemException(null, null, e.getMessage());
    exception.initCause(e);
    throw exception;
}
 
Example #27
Source File: SuccessTest.java    From cyclops with Apache License 2.0 5 votes vote down vote up
@Test
public void testRecoverFor() {
	Try<Integer,IOException> success = Try.success(20);
	assertThat(success.recoverFor(FileSystemException.class, e-> 10),equalTo(Try.success(20)));
	assertThat(success.recoverFor(FileNotFoundException.class, e-> 15),equalTo(Try.success(20)));
	assertThat(success.recoverFor(IOException.class,e->30),equalTo(success));
}
 
Example #28
Source File: SFTPEnvironment.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
FileSystemException asFileSystemException(Exception e) throws FileSystemException {
    if (e instanceof FileSystemException) {
        throw (FileSystemException) e;
    }
    FileSystemException exception = new FileSystemException(null, null, e.getMessage());
    exception.initCause(e);
    throw exception;
}
 
Example #29
Source File: JimfsUnixLikeFileSystemTest.java    From jimfs with Apache License 2.0 5 votes vote down vote up
@Test
public void testLink_failsForNonRegularFile() throws IOException {
  Files.createDirectory(path("/dir"));

  try {
    Files.createLink(path("/link"), path("/dir"));
    fail();
  } catch (FileSystemException expected) {
    assertEquals("/link", expected.getFile());
    assertEquals("/dir", expected.getOtherFile());
  }

  assertThatPath("/link").doesNotExist();
}
 
Example #30
Source File: SFTPFileSystemTest.java    From sftp-fs with Apache License 2.0 5 votes vote down vote up
@Test
public void testDeleteRoot() {

    FileSystemException exception = assertThrows(FileSystemException.class, () -> fileSystem.delete(createPath("/")));
    assertEquals("/", exception.getFile());

    verify(getExceptionFactory()).createDeleteException(eq("/"), any(SftpException.class), eq(true));
}