Java Code Examples for java.nio.file.FileSystemException

The following examples show how to use java.nio.file.FileSystemException. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
@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 2
Source Project: openjdk-jdk9   Source File: SymLinkTest.java    License: 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 Project: geoportal-server-harvester   Source File: SinkFile.java    License: 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 4
Source Project: mycore   Source File: MCRIFSFileSystem.java    License: 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 5
Source Project: flink   Source File: FileUtilsTest.java    License: 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 6
Source Project: jimfs   Source File: FileSystemView.java    License: 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 7
Source Project: sftp-fs   Source File: SFTPFileSystemTest.java    License: 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 8
Source Project: sftp-fs   Source File: SFTPFileSystemTest.java    License: 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 Project: sftp-fs   Source File: SFTPFileSystemTest.java    License: 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 10
Source Project: sftp-fs   Source File: SFTPFileSystemTest.java    License: 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 11
Source Project: sftp-fs   Source File: SFTPFileSystemTest.java    License: 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 12
Source Project: update4j   Source File: Warning.java    License: 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 13
Source Project: pgpverify-maven-plugin   Source File: PGPKeysCache.java    License: Apache License 2.0 5 votes vote down vote up
private static void moveFile(File source, File destination) throws IOException {
    try {
        Files.move(source.toPath(), destination.toPath(), StandardCopyOption.REPLACE_EXISTING);
    } catch (FileSystemException fse) {
        // on windows system we can get:
        // The process cannot access the file because it is being used by another process.
        // so wait ... and try again
        sleepUninterruptibly(250L + new SecureRandom().nextInt(1000), TimeUnit.MILLISECONDS);
        Files.move(source.toPath(), destination.toPath(), StandardCopyOption.REPLACE_EXISTING);
    }
}
 
Example 14
Source Project: JavaRushTasks   Source File: Solution.java    License: MIT License 5 votes vote down vote up
public void methodThrowExceptions() throws CharConversionException, FileSystemException, IOException {
    int i = (int) (Math.random() * 3);
    if (i == 0)
        throw new CharConversionException();
    if (i == 1)
        throw new FileSystemException("");
    if (i == 2)
        throw new IOException();
}
 
Example 15
@Override
public BackgroundException map(final IOException e) {
    final StringBuilder buffer = new StringBuilder();
    this.append(buffer, e.getMessage());
    if(e instanceof NoSuchFileException) {
        return new NotfoundException(buffer.toString(), e);
    }
    if(e instanceof FileSystemException) {
        return new AccessDeniedException(buffer.toString(), e);
    }
    return this.wrap(e, buffer);
}
 
Example 16
Source Project: Bytecoder   Source File: JrtFileSystem.java    License: Apache License 2.0 5 votes vote down vote up
byte[] getFileContent(JrtPath path) throws IOException {
    Node node = checkNode(path);
    if (node.isDirectory()) {
        throw new FileSystemException(path + " is a directory");
    }
    //assert node.isResource() : "resource node expected here";
    return image.getResource(node);
}
 
Example 17
Source Project: openjdk-jdk9   Source File: JrtFileSystem.java    License: GNU General Public License v2.0 5 votes vote down vote up
byte[] getFileContent(JrtPath path) throws IOException {
    Node node = checkNode(path);
    if (node.isDirectory()) {
        throw new FileSystemException(path + " is a directory");
    }
    //assert node.isResource() : "resource node expected here";
    return image.getResource(node);
}
 
Example 18
Source Project: sftp-fs   Source File: IdentityTest.java    License: Apache License 2.0 5 votes vote down vote up
private void testLoginFailure(final Identity identity) {
    SFTPEnvironment env = createEnv()
            .withUserInfo(null)
            .withIdentity(identity);
    FileSystemException exception = assertThrows(FileSystemException.class, () -> new SFTPFileSystemProvider().newFileSystem(getURI(), env));
    assertThat(exception.getCause(), instanceOf(JSchException.class));
    assertEquals("USERAUTH fail", exception.getMessage());
}
 
Example 19
Source Project: mycore   Source File: MCRIFSFileSystem.java    License: GNU General Public License v3.0 5 votes vote down vote up
@Override
public void createRoot(String owner) throws FileSystemException {
    MCRDirectory rootDirectory = MCRDirectory.getRootDirectory(owner);
    MCRPath rootPath = getPath(owner, "", this);
    if (rootDirectory != null) {
        throw new FileAlreadyExistsException(rootPath.toString());
    }
    try {
        rootDirectory = new MCRDirectory(owner);
    } catch (RuntimeException e) {
        LogManager.getLogger(getClass()).warn("Catched run time exception while creating new root directory.", e);
        throw new FileSystemException(rootPath.toString(), null, e.getMessage());
    }
    LogManager.getLogger(getClass()).info("Created root directory: {}", rootPath);
}
 
Example 20
Source Project: JavaExercises   Source File: Solution.java    License: GNU General Public License v2.0 5 votes vote down vote up
public static void main(String[] args) {
    try {

        processExceptions();

    } catch (FileSystemException e) {
        BEAN.log(e);
    }
}
 
Example 21
Source Project: JavaExercises   Source File: Solution.java    License: GNU General Public License v2.0 5 votes vote down vote up
public void methodThrowExceptions() throws CharConversionException, FileSystemException, IOException {
    int i = (int) (Math.random() * 3);
    if (i == 0)
        throw new CharConversionException();
    if (i == 1)
        throw new FileSystemException("");
    if (i == 2)
        throw new IOException();
}
 
Example 22
Source Project: piper   Source File: MkdirTests.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void test2 () throws IOException {
  Assertions.assertThrows(FileSystemException.class,() -> {
    Mkdir mkdir = new Mkdir();
    SimpleTaskExecution task = new SimpleTaskExecution();
    task.set("path", "/no/such/thing");
    mkdir.handle(task);
  });
}
 
Example 23
Source Project: lucene-solr   Source File: HandleLimitFS.java    License: Apache License 2.0 5 votes vote down vote up
@Override
protected void onOpen(Path path, Object stream) throws IOException {
  if (count.incrementAndGet() > limit) {
    count.decrementAndGet();
    throw new FileSystemException(path.toString(), null, "Too many open files");
  }
}
 
Example 24
Source Project: sftp-fs   Source File: DefaultFileSystemExceptionFactory.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 * <p>
 * If the {@link SftpException#id id} of the {@link SftpException} is not {@link ChannelSftp#SSH_FX_NO_SUCH_FILE} or
 * {@link ChannelSftp#SSH_FX_PERMISSION_DENIED}, this default implementation does not return a {@link FileSystemException}, but a
 * {@link NotLinkException} instead.
 */
@Override
public FileSystemException createReadLinkException(String link, SftpException exception) {
    if (exception.id == ChannelSftp.SSH_FX_NO_SUCH_FILE || exception.id == ChannelSftp.SSH_FX_PERMISSION_DENIED) {
        return asFileSystemException(link, null, exception);
    }
    final FileSystemException result = new NotLinkException(link, null, exception.getMessage());
    result.initCause(exception);
    return result;
}
 
Example 25
Source Project: jimfs   Source File: JimfsUnixLikeFileSystemTest.java    License: 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 26
Source Project: sftp-fs   Source File: SFTPEnvironment.java    License: 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 27
Source Project: sftp-fs   Source File: SSHChannelPool.java    License: 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 28
Source Project: buck   Source File: WatchmanBuildPackageComputation.java    License: 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 29
Source Project: buck   Source File: WatchmanBuildPackageComputation.java    License: 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 30
Source Project: sftp-fs   Source File: SFTPFileSystemTest.java    License: 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"));
}