org.conqat.lib.commons.filesystem.NonThrowingFileVisitor Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of teamscale-lib-commons Show documentation
Show all versions of teamscale-lib-commons Show documentation
Provides common utility functions
package org.conqat.lib.commons.filesystem;
import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import org.checkerframework.checker.nullness.qual.NonNull;
import org.conqat.lib.commons.assertion.CCSMAssert;
import org.conqat.lib.commons.collections.PairList;
import org.conqat.lib.commons.function.ConsumerWithException;
/**
* {@link java.nio.file.FileVisitor} that does not throw any {@link IOException}. Instead, any
* {@link IOException} is collected together with the respective file and can be retrieved using
* {@link #getFailedFiles()}.
*
* @param
* file type
*/
public class NonThrowingFileVisitor extends SimpleFileVisitor {
/**
* Contains all files for which the traversal failed, together with the respective
* {@link IOException}.
*/
private final PairList failedFiles = new PairList<>();
/**
* Actual consumer of the file in {@link #visitFile(Object, BasicFileAttributes)}.
*/
private final ConsumerWithException fileConsumer;
public NonThrowingFileVisitor(@NonNull ConsumerWithException fileConsumer) {
CCSMAssert.isNotNull(fileConsumer, () -> String.format("Expected \"%s\" to be not null", "fileConsumer"));
this.fileConsumer = fileConsumer;
}
@Override
public FileVisitResult visitFile(T file, BasicFileAttributes attrs) {
try {
fileConsumer.accept(file);
} catch (IOException e) {
// Do not throw this Exception, as this will abort the complete walk
// (and will not be handled by visitFileFailed)
handleIoException(file, e);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(T file, IOException exc) {
handleIoException(file, exc);
return FileVisitResult.CONTINUE;
}
private void handleIoException(T file, IOException exception) {
// Do not throw this (or any other) Exception, as this will abort the complete
// file walk, and may confuse users (TS-30138).
// Instead, accept that this may lead to slightly incorrect results and let the
// caller decide how to proceed
failedFiles.add(file, exception);
}
/** @see #failedFiles */
public PairList getFailedFiles() {
return failedFiles;
}
}