public void testFileSystemExceptions() throws IOException { for (FileSystemException ex : Arrays.asList(new FileSystemException("a", "b", "c"), new NoSuchFileException("a", "b", "c"), new NotDirectoryException("a"), new DirectoryNotEmptyException("a"), new AtomicMoveNotSupportedException("a", "b", "c"), new FileAlreadyExistsException("a", "b", "c"), new AccessDeniedException("a", "b", "c"), new FileSystemLoopException("a"))) { FileSystemException serialize = serialize(ex); assertEquals(serialize.getClass(), ex.getClass()); assertEquals("a", serialize.getFile()); if (serialize.getClass() == NotDirectoryException.class || serialize.getClass() == FileSystemLoopException.class || serialize.getClass() == DirectoryNotEmptyException.class) { assertNull(serialize.getOtherFile()); assertNull(serialize.getReason()); } else { assertEquals(serialize.getClass().toString(), "b", serialize.getOtherFile()); assertEquals(serialize.getClass().toString(), "c", serialize.getReason()); } } }
/** * Clear this ReactiveJournal's {@link #getDir() data directory} from ReactiveJournal-specific binary files, and remove it as * well (but only if it has become empty). If other files have been created inside the data directory, it is the * responsibility of the user to delete them AND the data directory. * * @throws IOException in case of directory traversal or file deletion problems */ public void clearCache() throws IOException { LOG.info("Deleting existing recording [{}]", dir); Path journalDir = Paths.get(dir); if(Files.exists(journalDir)) { Files.walk(journalDir) .map(Path::toFile) .filter(f -> f.isFile() && f.getName().endsWith(".cq4")) .peek(f -> LOG.info("Removing {}", f.getName())) .forEach(File::delete); try { Files.deleteIfExists(journalDir); } catch (DirectoryNotEmptyException e) { LOG.info("Directory does not only contain cq4 files, not deleted"); } } }
/** * * @param projectName The name of the project to create * */ public void startProject(String projectName) { PROJECT_NAME = projectName; File projectFolder = new File(projectName); if (projectFolder.exists()) { try { throw new DirectoryNotEmptyException(projectName); } catch (DirectoryNotEmptyException ex) { Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex); } } else { projectFolder.mkdir(); System.out.println("Project " + projectName + " Successfully Created at " + projectFolder.getAbsolutePath()); PROJECT_ROOT = projectFolder.getAbsolutePath() + File.separatorChar; createWorkingPackages(projectFolder.getAbsolutePath() + File.separatorChar); } }
@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); }
@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; } }
@Test(expected = DirectoryNotEmptyException.class) public void safeCopyFails() throws Exception { Path tmp = Files.createTempDirectory("test"); tmp.toFile().deleteOnExit(); Path f1 = tmp.resolve("f1"); f1.toFile().deleteOnExit(); Path d1 = tmp.resolve("d1"); d1.toFile().deleteOnExit(); Files.createFile(f1); // Make d1 difficult to overwrite Files.createDirectory(d1); Files.createFile(d1.resolve("child")); try { // Files.copy(f1, d1, StandardCopyOption.REPLACE_EXISTING); Bundles.safeCopy(f1, d1); } finally { assertEquals(Arrays.asList("d1", "f1"), ls(tmp)); assertTrue(Files.exists(f1)); assertTrue(Files.isDirectory(d1)); } }
void delete(EphemeralFsPath path) throws IOException { synchronized(fsLock) { ResolvedPath resolvedPath = ResolvedPath.resolve(path, true); if(resolvedPath.hasTarget()) { INode iNode = resolvedPath.getTarget(); if(iNode.isDir() && !iNode.isEmpty()) { throw new DirectoryNotEmptyException(path.toString()); } } if(!resolvedPath.didResolve()) { throw new NoSuchFileException(path.toString()); } if(getSettings().isWindows() && resolvedPath.getResolvedProperties().getDosIsReadOnly()) { throw new AccessDeniedException(path.toString()); } resolvedPath.getParent().remove(resolvedPath.getPath().getFileName()); } }
@Test public void testCopyDirFailsDestIfDestNotEmptyEvenWithReplaceExisting() throws Exception { Path source = root.resolve("source"); Path dest = root.resolve("dest"); Files.createDirectories(source); Files.createDirectories(dest); Files.createDirectories(dest.resolve("destChild")); try { Files.copy(source, dest, StandardCopyOption.REPLACE_EXISTING); fail(); } catch(DirectoryNotEmptyException e) { //pass } }
@Test public void testDirMoveAlreadyExistsNotEmpty() throws Exception { Path sourceDir = Files.createDirectory(root.resolve("sourceDir")); Files.createFile(sourceDir.resolve("aFile")); Path targetDir = Files.createDirectory(root.resolve("targetDir")); Files.createFile(targetDir.resolve("aFile")); try { Files.move(sourceDir, targetDir, StandardCopyOption.REPLACE_EXISTING); fail(); } catch(DirectoryNotEmptyException e) { //pass } }
@Override protected void execute(ElfinderStorage elfinderStorage, HttpServletRequest request, JSONObject json) throws Exception { String[] targets = request.getParameterValues(ElFinderConstants.ELFINDER_PARAMETER_TARGETS); List<String> removed = new ArrayList<>(); for (String target : targets) { VolumeHandler vh = findTarget(elfinderStorage, target); try { vh.delete(); removed.add(vh.getHash()); } catch (DirectoryNotEmptyException dne) { json.put(ElFinderConstants.ELFINDER_JSON_RESPONSE_ERROR, "Directory not empty!"); } } json.put(ElFinderConstants.ELFINDER_JSON_RESPONSE_REMOVED, removed.toArray()); }
/** * Loads all XML files from {@code path} and calls {@link #parseFile(File)} for each one of them. * @param dir the directory object to scan. * @param recursive parses all sub folders if there is. * @return {@code false} if it fails to find the directory, {@code true} otherwise. */ protected boolean parseDirectory(File dir, boolean recursive) { if (!dir.exists()) { VotingRewardInterface.getInstance().logWarning(getClass().getSimpleName() + ": Folder " + dir.getAbsolutePath() + " doesn't exist!", new DirectoryNotEmptyException(dir.getAbsolutePath())); return false; } final File[] listOfFiles = dir.listFiles(); for (File f : listOfFiles) { if (recursive && f.isDirectory()) { parseDirectory(f, recursive); } else if (getCurrentFileFilter().accept(f)) { parseFile(f); } } return true; }
@Test(expected = DirectoryNotEmptyException.class) public void testDirectoryNotEmptyExceptionOnDelete() throws URISyntaxException, IOException { // Create the directory URI uriDir = clusterUri .resolve("/tmp/testDirectoryNotEmptyExceptionOnDelete"); Path pathDir = Paths.get(uriDir); // Check that directory doesn't exists if (Files.exists(pathDir)) { Files.delete(pathDir); } Files.createDirectory(pathDir); assertTrue(Files.exists(pathDir)); // Create the file Path path = pathDir.resolve("test_file"); Files.createFile(path); assertTrue(Files.exists(path)); Files.delete(pathDir); // this one generate the exception assertFalse(Files.exists(path)); }
/** * Test for * {@link Files#createDirectories(Path, java.nio.file.attribute.FileAttribute...) * Files.createDirectories()}. * * @throws IOException */ @Test(expected = DirectoryNotEmptyException.class) public void testCreateDirectories() throws IOException { Path rootPath = Paths.get(clusterUri); Path dir = rootPath.resolve(rootPath.resolve("tmp/1/2/3/4/5")); Path dir2 = Files.createDirectories(dir); assertTrue(Files.exists(dir2)); Files.delete(rootPath.resolve("tmp/1/2/3/4/5")); Files.delete(rootPath.resolve("tmp/1/2/3/4")); Files.delete(rootPath.resolve("tmp/1/2/3")); Files.delete(rootPath.resolve("tmp/1/2")); // Throws Files.delete(rootPath.resolve("tmp")); }
private void removeDirs(String d) { try { Files.deleteIfExists(Paths.get(PATH + SEPARATOR + d)); } catch (IOException e) { if(!(e instanceof DirectoryNotEmptyException)) { e.printStackTrace(); } } }
private void removeFilesAndEmptyDirs(List<String> dirsToRetry, Map.Entry<String, String> k) { try { Files.deleteIfExists(Paths.get(PATH + SEPARATOR + k.getKey())); } catch (IOException e) { if(e instanceof DirectoryNotEmptyException) { dirsToRetry.add(k.getKey()); } else { e.printStackTrace(); } } }
/** * Creates a response handler that writes all response content to the specified file. If the file already exists * then a {@link java.nio.file.FileAlreadyExistsException} will be thrown. * * @param path Path to file to write to. * @param <ResponseT> Type of unmarshalled response POJO. * @return StreamingResponseHandler instance. */ static <ResponseT> StreamingResponseHandler<ResponseT, ResponseT> toFile(Path path) { return (resp, in) -> { try { Files.copy(in, path); return resp; } catch (IOException copyException) { String copyError = "Failed to read response into file: " + path; // If the write failed because of the state of the file, don't retry the request. if (copyException instanceof FileAlreadyExistsException || copyException instanceof DirectoryNotEmptyException) { throw new IOException(copyError, copyException); } // Try to clean up the file so that we can retry the request. If we can't delete it, don't retry the request. try { Files.deleteIfExists(path); } catch (IOException deletionException) { Logger.loggerFor(StreamingResponseHandler.class) .error(() -> "Failed to delete destination file '" + path + "' after reading the service response " + "failed.", deletionException); throw new IOException(copyError + ". Additionally, the file could not be cleaned up (" + deletionException.getMessage() + "), so the request will not be retried.", copyException); } // Retry the request throw new RetryableException(copyError, copyException); } }; }
@Test public void testDeleteWillNotDeleteADirectoryRecursively() throws IOException { String originalContent = "This is my content"; // Create a dir CloudPath dirPath = new CloudPath(containerPath, "subdir"); createDirectory(dirPath); // Create content in this dir String contentPathFilename = "subdir/cloud-file-channel-test.txt"; CloudPath contentPath1 = new CloudPath(dirPath, contentPathFilename); createRawContent(contentPath1.getPathName(), originalContent.getBytes("UTF-8")); assertFileExists(contentPath1); // Create subdir CloudPath dirPath2 = new CloudPath(containerPath, "subdir/subdir2"); impl.createDirectory(blobStoreContext, dirPath2); assertDirectoryExists(dirPath); // Create content in a subdir String contentPathFilename2 = "cloud-file-channel-test.txt"; CloudPath contentPath2 = new CloudPath(dirPath2, contentPathFilename2); createRawContent(contentPath2.getPathName(), originalContent.getBytes("UTF-8")); assertFileExists(contentPath2); // Create a control file outside of the main directory which should exist after the delete String controlFilePathString = "control-file-test.txt"; CloudPath controlFilePath = new CloudPath(dirPath, controlFilePathString); createRawContent(controlFilePath.getPathName(), originalContent.getBytes("UTF-8")); assertFileExists(controlFilePath); // Perform delete try { impl.delete(blobStoreContext, dirPath, EnumSet.noneOf(DeleteOption.class)); Assert.fail("Did not expect to be able to delete a non-empty directory"); } catch (DirectoryNotEmptyException e) { // OK } }
@Override public void delete(Path path) throws IOException { MCRPath mcrPath = MCRFileSystemUtils.checkPathAbsolute(path); MCRFilesystemNode child = resolvePath(mcrPath); if (child instanceof MCRDirectory) { if (((MCRDirectory) child).hasChildren()) { throw new DirectoryNotEmptyException(mcrPath.toString()); } } try { child.delete(); } catch (RuntimeException e) { throw new IOException("Could not delete: " + mcrPath, e); } }
/** * Removes the directory if and only if the directory is empty. */ @Override public boolean deleteEmptyDirectory(final Path directory) throws IOException { try { Files.deleteIfExists(directory); return true; } catch (DirectoryNotEmptyException e) { log.debug("Cannot remove non-empty directory {}", directory, e); return false; } }
@Override public FileVisitResult postVisitDirectory(Path dir, IOException exc) throws IOException { if (exc == null) { try { logger.debug("Deleting directory " + dir); Files.delete(dir); } catch (DirectoryNotEmptyException e) { logger.warn("Failed deleting non-empty directory " + dir); } return CONTINUE; } else { throw exc; } }
private void cleanDir(File rootDir) throws IOException { if(rootDir.isDirectory()) { try { Files.delete(Paths.get(rootDir.toURI())); } catch (DirectoryNotEmptyException dne) { for(File f : rootDir.listFiles()) { cleanDir(f); } rootDir.delete(); } } else { rootDir.delete(); } }
@Test public void testDeleteDirectoryNotEmptyFails() throws Exception { Path toDelete = root.resolve("deleteMe"); Files.createDirectory(toDelete); Files.createFile(toDelete.resolve("child")); try { Files.delete(toDelete); fail(); } catch(DirectoryNotEmptyException e) { //pass } }
@Test public void testDeleteNonEmptyDir() throws IOException { Files.createDirectory(moveTo.resolve("newDirectory")); Files.createDirectory(moveTo.resolve("newDirectory").resolve("child")); try { fixture.deleteDirectory(root.getFileSystem().getPath("newDirectory")); fail(); } catch(DirectoryNotEmptyException e) { //pass } }
/** * Deletes one or more items indicated by the given path. * * If path points to a directory: * -- if recursive is true, * all items under that path are recursively deleted followed by * deletion of the directory. * -- else, * -- the directory is deleted if it is empty, * -- else, an IOException is thrown. * * The recursive parameter is ignored for a file. * * @param path Path of the item to delete. * @param recursive If true, all sub-items are also deleted. * * @throws FileNotFoundException if the given path does not exist. * @throws IOException */ public void delete(URI path, boolean recursive) throws IOException { LOG.debug("delete({}, {})", path, recursive); Preconditions.checkNotNull(path); Preconditions.checkArgument(!path.equals(GCS_ROOT), "Cannot delete root path."); // Throw FileNotFoundException if the path does not exist. FileInfo fileInfo = getFileInfo(path); if (!fileInfo.exists()) { throw getFileNotFoundException(path); } List<URI> itemsToDelete = new ArrayList<>(); List<URI> bucketsToDelete = new ArrayList<>(); // Delete sub-items if it is a directory. if (fileInfo.isDirectory()) { List<URI> subpaths = listFileNames(fileInfo, recursive); if (recursive) { itemsToDelete.addAll(subpaths); } else { if (subpaths.size() > 0) { throw new DirectoryNotEmptyException("Cannot delete a non-empty directory."); } } } if (fileInfo.getItemInfo().isBucket()) { bucketsToDelete.add(fileInfo.getPath()); } else { itemsToDelete.add(fileInfo.getPath()); } deleteInternal(itemsToDelete, bucketsToDelete); }
@Test(timeout = 15000) public void remove() throws InterruptedException, IOException { File folder = drive.createFolder("test", testFolder); drive.createFile("test.txt", folder, getTestContent()); resetLocalState(); Path dirPath = mountPoint.resolve("test"); Path filePath = dirPath.resolve("test.txt"); assertThat(Files.exists(filePath), is(true)); try { Files.delete(dirPath); throw new AssertionError("non-empty directory must not have been deleted"); } catch (DirectoryNotEmptyException ignored) { } Files.delete(filePath); lifeCycleManager.waitUntilUploaderIsDone(); assertThat(Files.exists(filePath), is(false)); Files.delete(dirPath); lifeCycleManager.waitUntilUploaderIsDone(); assertThat(Files.exists(dirPath), is(false)); }
public void deleteFile(org.apache.hadoop.fs.Path hadoopPath, boolean failIfNotExists) throws IOException { checkWritable(); // If no exist if (!this.fs.exists(hadoopPath)) { if (failIfNotExists) throw new NoSuchFileException(hadoopPath.toString()); } else { FileStatus stat = this.fs.getFileStatus(hadoopPath); if (stat.isDirectory()) { FileStatus[] stats = this.fs.listStatus(hadoopPath); if (stats.length > 0) throw new DirectoryNotEmptyException(hadoopPath.toString()); } // Try to delete with no recursion this.fs.delete(hadoopPath, false); } /*IndexNode inode = getInode(hadoopPath); if (inode == null) { if (hadoopPath != null && hadoopPath.length == 0) throw new ZipException("root directory </> can't not be delete"); if (failIfNotExists) throw new NoSuchFileException(getString(hadoopPath)); } else { if (inode.isDir() && inode.child != null) throw new DirectoryNotEmptyException(getString(hadoopPath)); updateDelete(inode); }*/ }
@Test( expected = DirectoryNotEmptyException.class ) @Category( { Writable.class, Move.class } ) public void testMoveAlreadyThereNonEmptyDirectoryOverwrite() throws Exception { Files.createDirectory( tgt() ); Files.write( tgt().resolve( nameB() ), CONTENT ); Files.move( srcFile(), tgt(), StandardCopyOption.REPLACE_EXISTING ); }
@Test( expected = DirectoryNotEmptyException.class ) @Category( { Writable.class, Copy.class } ) public void testCopyFileReplaceExistingDoesNotOverwriteExistingNonEmptyDir() throws Exception { Path targetKid = tgt().resolve( "targetKid" ); Files.createDirectories( tgt() ); Files.write( targetKid, CONTENT ); Files.copy( srcFile(), tgt(), REPLACE_EXISTING ); }
@Test public void nonRecursiveModeFailsOnDirectories() throws Exception { Path dir = createNonEmptyDirectory(); RmStep step = RmStep.of( BuildCellRelativePath.fromCellRelativePath(filesystem.getRootPath(), filesystem, dir)); thrown.expect(DirectoryNotEmptyException.class); step.execute(context); }
@Override public void remove(Inode parent, String path) throws IOException { long parentInodeNumber = getInodeNumber(parent); Path parentPath = resolveInode(parentInodeNumber); Path targetPath = parentPath.resolve(path); long targetInodeNumber = resolvePath(targetPath); try { Files.delete(targetPath); } catch (DirectoryNotEmptyException e) { throw new NotEmptyException("dir " + targetPath + " is note empty"); } unmap(targetInodeNumber, targetPath); }
/** * Delete access is checked using {@link #checkAccess(BlobStoreContext, CloudPath, Set)} * with {@link AclEntryPermission#DELETE}. */ @Override public void delete(BlobStoreContext context, CloudPath path, EnumSet<DeleteOption> options) throws IOException { // A container if (path.getRoot() == null) { checkAccess(context, path, DELETE_DIRECTORY_STREAM_PERMS); LOG.debug("Deleting Container '{}'...", path); context.getBlobStore().deleteContainer(path.getContainerName()); LOG.debug("Deleted Container '{}' OK", path); return; } // Read the file/dir attributes CloudBasicFileAttributes readAttributes = readAttributes(context, CloudBasicFileAttributes.class, path); if (readAttributes.isDirectory()) { checkAccess(context, path, DELETE_DIRECTORY_STREAM_PERMS); // Delete all subpaths using the recursive directory listing Iterator<CloudPath> recursiveIterator = newDirectoryStream(context, path, null).iterator(); if (recursiveIterator.hasNext() && !options.contains(DeleteOption.RECURSIVE)) { throw new DirectoryNotEmptyException("Directory '" + path.toAbsolutePath() + "' is not empty and the recursive delete option has not been specified"); } LOG.debug("Deleting directory '{}' and all content recursively...", path); while (recursiveIterator.hasNext()) { delete(context, recursiveIterator.next(), options); } // Delete this path context.getBlobStore().deleteDirectory(path.getContainerName(), path.getPathName()); LOG.debug("Deleted directory '{}' and all content recursively OK", path); } else if (readAttributes.isRegularFile()) { checkAccess(context, path, DELETE_FILE_STREAM_PERMS); LOG.debug("Deleting BLOB file '{}'...", path); context.getBlobStore().removeBlob(path.getContainerName(), path.getPathName()); LOG.debug("Deleted BLOB file '{}' OK", path); } else if (readAttributes.isContainer()) { checkAccess(context, path, DELETE_DIRECTORY_STREAM_PERMS); LOG.debug("Deleting Container '{}'...", path); context.getBlobStore().deleteContainer(path.getContainerName()); LOG.debug("Deleted Container '{}' OK", path); } else { throw new IllegalArgumentException("Cannot delete this path '" + path.toString() + "' it is not a directory, file or container"); } }
@Test public void testDefaultCopyOfADirectoryWillFailIfTheTargetDirectoryIsNotEmptyAndTheRecursiveOptionHasNotBeenSpecified() throws IOException { String originalContent = "This is my content"; CloudPath dir1 = new CloudPath(containerPath, "subdir1"); impl.createDirectory(blobStoreContext, dir1); assertDirectoryExists(dir1); String testFileName = "subdir1/cloud-file-channel-test.txt"; createRawContent(testFileName, BlobAccess.PUBLIC_READ, originalContent.getBytes("UTF-8")); assertFileExists(testFileName); String testFileName2 = "subdir1/cloud-file-channel-test2.txt"; createRawContent(testFileName2, BlobAccess.PUBLIC_READ, originalContent.getBytes("UTF-8")); assertFileExists(testFileName2); CloudPath dir2 = new CloudPath(containerPath, "subdir1/subdir2"); impl.createDirectory(blobStoreContext, dir2); assertDirectoryExists(dir2); String testFileName3 = "subdir1/subdir2/cloud-file-channel-test3.txt"; createRawContent(testFileName3, BlobAccess.PUBLIC_READ, originalContent.getBytes("UTF-8")); assertFileExists(testFileName3); String targetDirName = "targetDir"; CloudPath targetDir = new CloudPath(containerPath, targetDirName); impl.createDirectory(blobStoreContext, targetDir); assertDirectoryExists(targetDir); String testFileName4 = "targetDir/cloud-file-channel-test3.txt"; createRawContent(testFileName4, BlobAccess.PUBLIC_READ, originalContent.getBytes("UTF-8")); assertFileExists(testFileName4); try { impl.copy(blobStoreContext, dir1, targetDir, Sets.newHashSet(StandardCopyOption.COPY_ATTRIBUTES, StandardCopyOption.REPLACE_EXISTING)); Assert.fail("Did not expect the copy to succeed"); } catch (DirectoryNotEmptyException e) { // OK } }
private void copyToTarget( AbstractPath target, CopyOption... options ) throws IOException { boolean replaceExisting = false; for( CopyOption opt: options ) { if( opt == REPLACE_EXISTING ) { replaceExisting = true; } } // attributes of source file BasicFileAttributes attrs = getAttributes(); // check if target exists boolean exists; if( replaceExisting ) { try { target.deleteIfExists(); exists = false; } catch( DirectoryNotEmptyException x ) { exists = true; } } else { exists = target.exists(); } if( exists ) { throw new FileAlreadyExistsException( target.toString() ); } if( attrs.isDirectory() ) { // create directory or file target.createDirectory(); } else { try( InputStream is = fs.getFileSystemIO().newInputStream( getResolvedPath() ); OutputStream os = target.newOutputStream() ) { byte[] buf = new byte[8192]; int n; while( (n = is.read( buf )) != -1 ) { os.write( buf, 0, n ); } } } }
@Override public void delete(Path path) throws IOException { JPath jPath = (JPath) path; BfsFileSync file = jPath.getBfsFile(); ResultFuture<Boolean> result = new ResultFuture<>(); String []list = file.list(); if (list.length != 0) { throw new DirectoryNotEmptyException(path.toUri().toString()); } file.remove(result); boolean isSuccessful; try { isSuccessful = result.get(10, TimeUnit.SECONDS); } catch (Exception e) { if (e instanceof IOException) { throw (IOException) e; } else { if (e instanceof ServiceException) { Throwable cause = ((ServiceException) e).unwrap(); if (cause instanceof IOException) { throw (IOException) cause; } } throw new IOException(e); } } if (! isSuccessful) { throw new IOException(L.l("failed to delete file: {0}", path)); } }
void move(EphemeralFsPath source, EphemeralFsPath target, CopyOption[] options) throws IOException { EnumSet<StandardCopyOption> optionsSet = EnumSet.noneOf(StandardCopyOption.class); if(options != null) { for(CopyOption option : options) { if(option instanceof StandardCopyOption) { optionsSet.add((StandardCopyOption) option); } else { throw new IllegalArgumentException("unrecognized option:" + option); } } } if(isSameFile(source, target)) { return; } synchronized(fsLock) { ResolvedPath sourceResolved = ResolvedPath.resolve(source, true); ResolvedPath targetResolved = ResolvedPath.resolve(target); if(!sourceResolved.hasTarget() && !sourceResolved.resolvedToSymbolicLink()) { throw new NoSuchFileException(source.toString()); } if(sourceResolved.hasTarget() && sourceResolved.getTarget() == root) { throw new IOException("cant move root"); } if(!targetResolved.hasValidParent()) { throw new NoSuchFileException(target.toString()); } if(targetResolved.hasTarget()) { if(!optionsSet.contains(StandardCopyOption.REPLACE_EXISTING) && //ATOMIC_MOVE on unix at least implies replace existing !optionsSet.contains(StandardCopyOption.ATOMIC_MOVE)) { throw new FileAlreadyExistsException(target.toString()); } if(getSettings().isWindows() && optionsSet.contains(StandardCopyOption.ATOMIC_MOVE)) { throw new AccessDeniedException(target.toString()); } if(targetResolved.getTarget().isDir() && !targetResolved.getTarget().isEmpty()) { throw new DirectoryNotEmptyException(target.toString()); } //remove target targetResolved.getParent().remove(target.getFileName()); } if(sourceResolved.resolvedToSymbolicLink()) { targetResolved.getParent().addSymlink(target.getFileName(), sourceResolved.getRawSymbolicLink()); } else { targetResolved.getParent().add(target.getFileName(), sourceResolved.getTarget()); } sourceResolved.getParent().remove(source.getFileName()); } }
@Test @Category( { Writable.class, Delete.class } ) public void testDeleteNonEmptyDirectoryThrows() throws IOException { assertThatThrownBy( () -> Files.delete( childGetParent( fileTAB() ))).isInstanceOf( DirectoryNotEmptyException.class ); }
/** * Checks that given directory is empty, throwing {@link DirectoryNotEmptyException} if not. */ private void checkEmpty(Directory dir, Path pathForException) throws FileSystemException { if (!dir.isEmpty()) { throw new DirectoryNotEmptyException(pathForException.toString()); } }