protected void watchDir(Path dir) throws IOException { LOG.debug("Registering watch for {}", dir); if (Thread.currentThread().isInterrupted()) { LOG.debug("Skipping adding watch since current thread is interrupted."); } // check if directory is already watched // on Windows, check if any parent is already watched for (Path path = dir; path != null; path = FILE_TREE_WATCHING_SUPPORTED ? path.getParent() : null) { WatchKey previousWatchKey = watchKeys.get(path); if (previousWatchKey != null && previousWatchKey.isValid()) { LOG.debug("Directory {} is already watched and the watch is valid, not adding another one.", path); return; } } int retryCount = 0; IOException lastException = null; while (retryCount++ < 2) { try { WatchKey watchKey = dir.register(watchService, WATCH_KINDS, WATCH_MODIFIERS); watchKeys.put(dir, watchKey); return; } catch (IOException e) { LOG.debug("Exception in registering for watching of " + dir, e); lastException = e; if (e instanceof NoSuchFileException) { LOG.debug("Return silently since directory doesn't exist."); return; } if (e instanceof FileSystemException && e.getMessage() != null && e.getMessage().contains("Bad file descriptor")) { // retry after getting "Bad file descriptor" exception LOG.debug("Retrying after 'Bad file descriptor'"); continue; } // Windows at least will sometimes throw odd exceptions like java.nio.file.AccessDeniedException // if the file gets deleted while the watch is being set up. // So, we just ignore the exception if the dir doesn't exist anymore if (!Files.exists(dir)) { // return silently when directory doesn't exist LOG.debug("Return silently since directory doesn't exist."); return; } else { // no retry throw e; } } } LOG.debug("Retry count exceeded, throwing last exception"); throw lastException; }
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()); } } }
/** * Deletes the given file or directory. * If the file is a directory, it must be empty. * * @param file the file or directory. * Note that although this just needs to be a plain {@code File} * object, archive files and entries are only supported for * instances of {@code TFile}. * @throws IOException if any I/O error occurs. * @see <a href="#bulkIOMethods">Bulk I/O Methods</a> */ @FsAssertion(atomic=YES, consistent=YES, isolated=YES) @SuppressWarnings("AccessingNonPublicFieldOfAnotherObject") public static void rm(File file) throws IOException { if (file instanceof TFile) { TFile tfile = (TFile) file; if (null != tfile.innerArchive) { tfile.innerArchive.getController().unlink( getAccessPreferences(), tfile.getNodeName()); return; } file = tfile.file; } if (!file.delete()) throw new FileSystemException(file.getPath(), null, "Cannot delete!"); }
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(); }
@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 void copyIfLocked(final Path source, final Path target, final Mover mover) throws IOException { checkNotNull(source); checkNotNull(target); try { mover.accept(source, target); } catch (AtomicMoveNotSupportedException atomicMoveNotSupported) { throw atomicMoveNotSupported; } catch (FileSystemException e) { // NOSONAR // Windows can throw a FileSystemException on move or moveAtomic // if the file is in use; in this case, copy and attempt to delete // source log.warn("Using copy to move {} to {}", source, target); copy(source, target); try { delete(source); } catch (IOException deleteException) { // NOSONAR log.error("Unable to delete {} after move: {}", source, deleteException.getMessage()); } } }
/** * Folder to which we save all the data * * @param folder target folder */ public FilePersister(File folder) throws FileSystemException { if (!folder.exists() && !folder.mkdir()) { throw new FileSystemException("Can't create target directory"); } if (!folder.isDirectory()) { throw new FileSystemException("Target is not a folder"); } //Creating subdirectories playlists = new File(getChildPath(folder.toString(), "playlists")); segments = new File(getChildPath(folder.toString(), "segments")); if ((!playlists.exists() && !playlists.mkdir()) || (!segments.exists() && !segments.mkdir())) { throw new FileSystemException("Can't create subdirectories"); } if (!playlists.isDirectory() || !segments.isDirectory()) { throw new FileSystemException("Sanity check #1 failed"); } }
/** * Clears all the existing stub configurations of Wilma. * * @throws Exception in case of an error. */ @Test public void testClearAllStubConfigAndUpload() throws Exception { //clear all stubconfig RequestParameters requestParameters = createRequestParameters(); ResponseHolder responseVersion = callWilmaWithPostMethod(requestParameters); //Get the actual DialogDescriptors String answer = responseVersion.getResponseMessage(); for (String groupName : getGroupNamesFromJson(answer)) { MultiStubRequestParameters multiStubRequestParameters = createMultiStubRequestParameters(groupName); callWilmaWithPostMethod(multiStubRequestParameters); //Delete the uploaded stub configuration logComment(groupName + "'s config has been dropped."); } //upload preserved stubconfig uploadStubConfigToWilmaAndAllowEmptyStuvConfig(STUB_CONFIG); //if we are here, then the stub config is restored, so we can delete it Path path = FileSystems.getDefault().getPath(STUB_CONFIG); try { Files.deleteIfExists(path); } catch (FileSystemException e) { logComment("Ups, cannot delete the file, reason: " + e.getLocalizedMessage()); } }
@Override public void deleteDirectory(Path path) throws IOException { EphemeralFsPath efsPath = cast(path); synchronized(efsPath.fs.fsLock) { EphemeralFsPath actualPath = translate(efsPath); if(actualPath == null) { throw new NoSuchFileException(path.toString()); } ResolvedPath resolved = ResolvedPath.resolve(actualPath, true); if(resolved.resolvedToSymbolicLink()) { throw new FileSystemException("symlink: Not a directory"); } if(!resolved.getTarget().isDir()) { throw new FileSystemException(path + ": Not a directory"); } actualPath.fs.delete(actualPath); return; } }
void createDirectory(EphemeralFsPath dir, FileAttribute<?>... attrs) throws IOException { dir = dir.toAbsolutePath(); synchronized(fsLock) { //this is root if(dir.getParent() == null) { throw new FileAlreadyExistsException(dir.toString()); } ResolvedPath resolvedPath = ResolvedPath.resolve(dir.getParent(), false); if(!resolvedPath.hasTarget()) { throw new NoSuchFileException(dir.getParent().toString()); } if(!resolvedPath.getTarget().isDir()) { throw new FileSystemException(dir.getParent() + " : is Not a directory"); } resolvedPath.getTarget().addDir(dir.getFileName(), new FilePermissions(true, attrs)); } }
void createLink(EphemeralFsPath link, EphemeralFsPath existing) throws IOException { synchronized(fsLock) { EphemeralFsPath dir = link.getParent(); ResolvedPath resolvedPath = ResolvedPath.resolve(dir, false); if(!resolvedPath.hasTarget()) { throw new NoSuchFileException(dir.toString()); } if(!resolvedPath.getTarget().isDir()) { throw new FileSystemException(dir + " : is Not a directory"); } ResolvedPath existingResolved = ResolvedPath.resolve(existing); if(!existingResolved.hasTarget()) { throw new NoSuchFileException(link.toString()); } if(existingResolved.getTarget().isDir()) { throw new FileSystemException(link + " -> " + existing + ": Operation not permitted"); } resolvedPath.getTarget().add(link.getFileName(), existingResolved.getTarget()); } }
private void assertCanAddChild(EphemeralFsPath name) throws IOException { if(isFile()) { throw new NotDirectoryException("can't add children to file"); } if(name.toString().equals(".") || name.toString().equals("..")) { throw new IllegalStateException("invalid path:" + name); } if(fs.getSettings().getMaxPathLength() != Long.MAX_VALUE && getPathToRoot().resolve(name).toString().length() > fs.getSettings().getMaxPathLength()) { throw new FileSystemException("Path too long"); } assertOnlyFileName(name); if(children.containsKey(name.toFileName())) { throw new FileAlreadyExistsException("a child with name:" + name + " already exists"); } }
public void notifyChange(EphemeralFsPath path) throws NoSuchFileException { ResolvedPath resolvedPath; try { resolvedPath = ResolvedPath.resolve(path.getParent(), false); } catch (FileSystemException e) { //we can't resolve the path //ignore and skip notifying return; } if(!resolvedPath.hasTarget()) { return; } if(resolvedPath.getTarget().isDir() && resolvedPath.getTarget().getName(this) != null) { EphemeralFsWatchEvent event = new EphemeralFsWatchEvent( path, StandardWatchEventKinds.ENTRY_MODIFY); fs.getWatchRegistry().hearChange(resolvedPath.getTarget(), event); } }
@Test public void testCopyFileFailsIfTargetParentIsFileExist() throws Exception { byte[] contents = new byte[20]; random.nextBytes(contents); Path source = root.resolve("source"); Path dest = root.resolve("dest").resolve("child"); Files.write(source, contents); Files.createFile(dest.getParent()); try { Files.copy(source, dest); fail(); } catch(FileSystemException e) { //pass } }
/** * Throws an exception indicating that one or more files couldn't be deleted. The thrown exception * contains all the exceptions in the given collection as suppressed exceptions. */ private static void throwDeleteFailed(Path path, Collection<IOException> exceptions) throws FileSystemException { // TODO(cgdecker): Should there be a custom exception type for this? // Also, should we try to include the Path of each file we may have failed to delete rather // than just the exceptions that occurred? FileSystemException deleteFailed = new FileSystemException( path.toString(), null, "failed to delete one or more files; see suppressed exceptions for details"); for (IOException e : exceptions) { deleteFailed.addSuppressed(e); } throw deleteFailed; }
@Override public FileChannel truncate( long size ) throws IOException { if( !isOpen() ) { throw new ClosedChannelException(); } if( !options.contains( WRITE ) ) { throw new NonWritableChannelException(); } if ( options.contains( APPEND )) { throw new FileSystemException( "can't truncate in append mode" ); } if( size < 0 ) { throw new IllegalArgumentException( "size must be non negative" ); } bytes.truncate( (int) size ); watchEventListener.signal( ENTRY_MODIFY ); return this; }
@Override public FileChannel truncate( long size ) throws IOException { if( !isOpen() ) { throw new ClosedChannelException(); } if( !options.contains( WRITE ) ) { throw new NonWritableChannelException(); } if ( options.contains( APPEND )) { throw new FileSystemException( "can't truncate in append mode" ); } if( size < 0 ) { throw new IllegalArgumentException( "size must be non negative" ); } bytes.truncate( (int) size ); // watchEventListener.signal( ENTRY_MODIFY ); return this; }
/** * Looks up the regular file at the given path, throwing an exception if the file isn't a regular * file. Returns null if the file did not exist. */ @Nullable private RegularFile lookUpRegularFile(JimfsPath path, Set<OpenOption> options) throws IOException { store.readLock().lock(); try { DirectoryEntry entry = lookUp(path, options); if (entry.exists()) { File file = entry.file(); if (!file.isRegularFile()) { throw new FileSystemException(path.toString(), null, "not a regular file"); } return open((RegularFile) file, options); } else { return null; } } finally { store.readLock().unlock(); } }
/** * 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 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 (FileSystemException e) { e.printStackTrace(); } } }
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(); }
/** Unchecked parameters version. */ private static void cp_r0( final boolean preserve, final File src, final File dst, final TArchiveDetector srcDetector, final TArchiveDetector dstDetector) throws IOException { if (src.isDirectory()) { final long srcLastModified = src.lastModified(); final boolean srcArchived = src instanceof TFile && null != ((TFile) src).getInnerArchive(); final boolean dstArchived = dst instanceof TFile && null != ((TFile) dst).getInnerArchive(); final boolean srcIsGhost = srcArchived && 0 >= srcLastModified; if (!srcIsGhost || !dstArchived || !TConfig.current().isLenient()) if (!dst.mkdir() && !dst.isDirectory()) throw new NotDirectoryException(dst.getPath()); final String[] members = src.list(); if (null == members) throw new FileSystemException(dst.getPath(), null, "Cannot list directory!"); if (!srcArchived && dstArchived) { // Create sorted entries if copying an ordinary directory to a // new archive. // This is a courtesy only, so natural order is sufficient. Arrays.sort(members); } for (final String member : members) cp_r0( preserve, new TFile(src, member, srcDetector), new TFile(dst, member, dstDetector), srcDetector, dstDetector); if (preserve && !srcIsGhost) if (!dst.setLastModified(srcLastModified)) throw new FileSystemException(dst.getPath(), null, "Cannot set last modification time!"); } else if (src.isFile()) { if (dst.exists() && !dst.isFile()) throw new FileSystemException(dst.getPath(), null, "Not a file!"); cp0(preserve, src, dst); } else if (src.exists()) { throw new FileSystemException(src.getPath(), null, "Cannot copy special file!"); } else { throw new NoSuchFileException(src.getPath()); } }
/** * Recursively deletes the given file or directory tree. * * @param file the file or directory tree to delete recursively. * @throws IOException if an elementary operation fails for any reason. */ static void rm_r(final File file, final TArchiveDetector detector) throws IOException { if (file.isDirectory()) { final String[] members = file.list(); if (null == members) throw new FileSystemException(file.getPath(), null, "Cannot list directory!"); for (final String member : members) rm_r(new TFile(file, member, detector), detector); } TFile.rm(file); }
/** * Ensures that a (virtual) directory with {@link #getPath() this path name} * exists in the (federated) file system. * * @param recursive whether or not any missing ancestor directories shall * get created if required. * @return {@code this} * @throws IOException if any I/O error occurs. */ @FsAssertion(consistent=YES, isolated=NO) public TFile mkdir(final boolean recursive) throws IOException { final TFile innerArchive = this.innerArchive; if (null != innerArchive) { if (recursive) { final TFile parent = getParentFile(); if (null != parent && !parent.exists()) parent.mkdir(recursive); } final FsController controller = innerArchive.getController(); final FsNodeName innerEntryName = getNodeName(); try { controller.make( getAccessPreferences(), innerEntryName, DIRECTORY, null); } catch (IOException ex) { final FsNode entry = controller .node(getAccessPreferences(), innerEntryName); if (null == entry || !entry.isType(DIRECTORY)) throw ex; } } else { final File dir = file; if (!(recursive ? dir.mkdirs() : dir.mkdir()) && !dir.isDirectory()) throw new FileSystemException(dir.getPath(), null, "Cannot create directory!"); } return this; }
/** * Moves the given source file or directory to the given destination file * or directory. * <p> * In certain cases, this method might perform a recursive copy-then-delete * operation rather than an atomic move operation. * In these cases, an attempt is made to copy all attributes of each * source file to the destination file, too. * Which attributes are actually copied is specific to the destination * file system driver implementation, but the minimum guarantee is to * copy the last modification time. * * @param src the source file or directory tree. * Note that although this just needs to be a plain {@code File}, * archive files and entries are only supported for instances of * this class. * @param dst the destination file or directory tree. * Note that although this just needs to be a plain {@code File}, * archive files and entries are only supported for instances of * this class. * @param detector the archive detector to use for detecting any archive * files <em>within</em> the source and destination directory * trees. * @throws IOException if any I/O error occurs. * @see <a href="#bulkIOMethods">Bulk I/O Methods</a> * @see <a href="#traversal">Traversing Directory Trees</a> */ @ExpertFeature( level=INTERMEDIATE, value=INJECTING_A_DIFFERENT_DETECTOR_FOR_THE_SAME_PATH_MAY_CORRUPT_DATA) @FsAssertion(consistent=YES) public static void mv( final File src, final File dst, final TArchiveDetector detector) throws IOException { final boolean srcArchived; final File srcDelegate; if (src instanceof TFile) { final TFile srcFile = (TFile) src; srcArchived = null != srcFile.getInnerArchive(); srcDelegate = srcFile.getFile(); } else { srcArchived = false; srcDelegate = src; } final boolean dstArchived; final File dstDelegate; if (dst instanceof TFile) { final TFile dstFile = (TFile) dst; dstArchived = null != dstFile.getInnerArchive(); dstDelegate = dstFile.getFile(); } else { dstArchived = false; dstDelegate = dst; } if (!srcArchived && !dstArchived) { if (srcDelegate.renameTo(dstDelegate)) return; throw new FileSystemException(src.getPath(), dst.getPath(), "Cannot rename."); } TBIO.mv(src, dst, detector); }
/** * Deletes the file or directory at the given {@code path} recursively. Deletes symbolic links, * not their targets (subject to the caveat below). * * <p>If an I/O exception occurs attempting to read, open or delete any file under the given * directory, this method skips that file and continues. All such exceptions are collected and, * after attempting to delete all files, an {@code IOException} is thrown containing those * exceptions as {@linkplain Throwable#getSuppressed() suppressed exceptions}. * * <h2>Warning: Security of recursive deletes</h2> * * <p>On a file system that supports symbolic links and does <i>not</i> support * {@link SecureDirectoryStream}, it is possible for a recursive delete to delete files and * directories that are <i>outside</i> the directory being deleted. This can happen if, after * checking that a file is a directory (and not a symbolic link), that directory is replaced by a * symbolic link to an outside directory before the call that opens the directory to read its * entries. * * <p>By default, this method throws {@link InsecureRecursiveDeleteException} if it can't * guarantee the security of recursive deletes. If you wish to allow the recursive deletes * anyway, pass {@link RecursiveDeleteOption#ALLOW_INSECURE} to this method to override that * behavior. * * @throws NoSuchFileException if {@code path} does not exist <i>(optional specific * exception)</i> * @throws InsecureRecursiveDeleteException if the security of recursive deletes can't be * guaranteed for the file system and {@link RecursiveDeleteOption#ALLOW_INSECURE} was not * specified * @throws IOException if {@code path} or any file in the subtree rooted at it can't be deleted * for any reason */ public static void deleteRecursively( Path path, RecursiveDeleteOption... options) throws IOException { Path parentPath = getParentPath(path); if (parentPath == null) { throw new FileSystemException(path.toString(), null, "can't delete recursively"); } Collection<IOException> exceptions = null; // created lazily if needed try { boolean sdsSupported = false; try (DirectoryStream<Path> parent = Files.newDirectoryStream(parentPath)) { if (parent instanceof SecureDirectoryStream) { sdsSupported = true; exceptions = deleteRecursivelySecure( (SecureDirectoryStream<Path>) parent, path.getFileName()); } } if (!sdsSupported) { checkAllowsInsecure(path, options); exceptions = deleteRecursivelyInsecure(path); } } catch (IOException e) { if (exceptions == null) { throw e; } else { exceptions.add(e); } } if (exceptions != null) { throwDeleteFailed(path, exceptions); } }
/** * Throws an exception indicating that one or more files couldn't be deleted. The thrown * exception contains all the exceptions in the given collection as suppressed exceptions. */ private static void throwDeleteFailed( Path path, Collection<IOException> exceptions) throws FileSystemException { // TODO(cgdecker): Should there be a custom exception type for this? // Also, should we try to include the Path of each file we may have failed to delete rather // than just the exceptions that occurred? FileSystemException deleteFailed = new FileSystemException(path.toString(), null, "failed to delete one or more files; see suppressed exceptions for details"); for (IOException e : exceptions) { deleteFailed.addSuppressed(e); } throw deleteFailed; }
@Bean public Boolean checkHost() throws FileSystemException { FsReady.checkFileSystemIsReady(10, new File(System.getProperty("java.io.tmpdir"))); UtcVerifier.checkHostTimezone(); Utf8Verifier.checkHostEncoding(); return true; }
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); }
@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 PathIndex build() throws FileSystemException { env = create().setMapSize( unit.toBytes( val ) ).setMaxDbs( 1 ).open( dbDir ); db = env.openDbi( "pathdb.db", MDB_CREATE ); return new LMDB(env, db, new PersistedStatisticsStore()); }
/** * Create a new trace project starting from the trace file (i.e. a .trace or * .tracez file) * * @param traceFile * the trace file * @return the trace project */ public static TraceProject open(File traceFile) { String extension = ""; try { extension = FileUtils.getExtension(traceFile); if (!extension.equals(TRACE) && !extension.equals(TRACEZ)) { throw new FileSystemException("Trace file error: unsupported extension"); } return new TraceProject(traceFile); } catch (Exception e) { throw new TurnusRuntimeException("The trace project " + traceFile + " cannot be opened: " + e.getMessage()); } }
@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()); }
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()); } }