下面列出了怎么用java.nio.file.FileSystemException的API类实例代码及写法,或者点击链接到github查看源代码。
@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();
}
}
}
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();
}
/**
* 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
}
}
}
}
@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);
}
/**
* 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());
}
/** 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");
}
}
@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")));
}
@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")));
}
@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")));
}
@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")));
}
@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")));
}
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");
}
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);
}
}
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();
}
@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);
}
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);
}
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);
}
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());
}
@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);
}
public static void main(String[] args) {
try {
processExceptions();
} catch (FileSystemException e) {
BEAN.log(e);
}
}
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();
}
@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);
});
}
@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");
}
}
/**
* {@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;
}
@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();
}
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;
}
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;
}
private FileSystemException enrichFileSystemException(FileSystemException exception) {
if (!(exception instanceof NotDirectoryException) && isNotADirectoryError(exception)) {
FileSystemException e = new NotDirectoryException(exception.getFile());
e.initCause(exception);
return e;
}
return exception;
}
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);
}
@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"));
}