* avoid potentially NULL-listFiles() calls

This commit is contained in:
Reinhard Pointner 2014-07-28 10:00:27 +00:00
parent 98633f7364
commit 90951f7989
11 changed files with 85 additions and 82 deletions

View File

@ -92,7 +92,7 @@ public class Main {
if (args.clearCache()) {
// clear preferences and cache
System.out.println("Clear cache and temporary files");
for (File folder : getApplicationFolder().getAbsoluteFile().listFiles(FOLDERS)) {
for (File folder : getChildren(getApplicationFolder().getAbsoluteFile(), FOLDERS)) {
if (matches("cache|temp|grape|reports|logs", folder.getName())) {
if (delete(folder)) {
System.out.println("* Delete " + folder);

View File

@ -150,7 +150,8 @@ public class CmdlineOperations implements CmdlineInterface {
return renameAll(renameMap, renameAction, ConflictAction.forName(conflict), null);
}
public List<File> renameSeries(Collection<File> files, RenameAction renameAction, ConflictAction conflictAction, File outputDir, ExpressionFormat format, EpisodeListProvider db, String query, SortOrder sortOrder, ExpressionFilter filter, Locale locale, boolean strict) throws Exception {
public List<File> renameSeries(Collection<File> files, RenameAction renameAction, ConflictAction conflictAction, File outputDir, ExpressionFormat format, EpisodeListProvider db, String query, SortOrder sortOrder, ExpressionFilter filter, Locale locale, boolean strict)
throws Exception {
CLILogger.config(format("Rename episodes using [%s]", db.getName()));
// ignore sample files
@ -344,10 +345,10 @@ public class CmdlineOperations implements CmdlineInterface {
// collect useful nfo files even if they are not part of the selected fileset
Set<File> effectiveNfoFileSet = new TreeSet<File>(nfoFiles);
for (File dir : mapByFolder(movieFiles).keySet()) {
addAll(effectiveNfoFileSet, dir.listFiles(NFO_FILES));
effectiveNfoFileSet.addAll(getChildren(dir, NFO_FILES));
}
for (File dir : filter(fileset, FOLDERS)) {
addAll(effectiveNfoFileSet, dir.listFiles(NFO_FILES));
effectiveNfoFileSet.addAll(getChildren(dir, NFO_FILES));
}
for (File nfo : effectiveNfoFileSet) {
@ -758,7 +759,7 @@ public class CmdlineOperations implements CmdlineInterface {
List<File> videoFiles = filter(filter(files, VIDEO_FILES), new FileFilter() {
// save time on repeating filesystem calls
private final Map<File, File[]> cache = new HashMap<File, File[]>();
private final Map<File, List<File>> cache = new HashMap<File, List<File>>();
private final SubtitleNaming naming = getSubtitleNaming(format);
@ -776,9 +777,9 @@ public class CmdlineOperations implements CmdlineInterface {
@Override
public boolean accept(File video) {
File[] subtitlesByFolder = cache.get(video.getParentFile());
List<File> subtitlesByFolder = cache.get(video.getParentFile());
if (subtitlesByFolder == null) {
subtitlesByFolder = video.getParentFile().listFiles(SUBTITLE_FILES);
subtitlesByFolder = getChildren(video.getParentFile(), SUBTITLE_FILES);
cache.put(video.getParentFile(), subtitlesByFolder);
}

View File

@ -112,11 +112,8 @@ public abstract class FolderWatchService implements Closeable {
}
private void watchFolderTree(File root) throws IOException {
File[] folders = root.listFiles(FOLDERS);
if (folders != null) {
for (File it : folders) {
watchFolderTree(it);
}
for (File it : getChildren(root, FOLDERS)) {
watchFolderTree(it);
}
startWatch(root);

View File

@ -501,7 +501,7 @@ public class MediaBindingBean {
if (hasExtension(mediaFile, "idx")) {
return Language.getLanguage(grepLanguageFromSUBIDX(mediaFile));
} else if (hasExtension(mediaFile, "sub")) {
for (File idx : mediaFile.getParentFile().listFiles(new ExtensionFileFilter("idx"))) {
for (File idx : getChildren(mediaFile.getParentFile(), new ExtensionFileFilter("idx"))) {
if (isDerived(idx, mediaFile)) {
return Language.getLanguage(grepLanguageFromSUBIDX(idx));
}
@ -807,7 +807,7 @@ public class MediaBindingBean {
// file is a subtitle, or nfo, etc
String baseName = stripReleaseInfo(FileUtilities.getName(mediaFile)).toLowerCase();
File[] videos = mediaFile.getParentFile().listFiles(VIDEO_FILES);
List<File> videos = getChildren(mediaFile.getParentFile(), VIDEO_FILES);
// find corresponding movie file
for (File movieFile : videos) {
@ -817,15 +817,15 @@ public class MediaBindingBean {
}
// still no good match found -> just take the most probable video from the same folder
if (videos.length > 0) {
sort(videos, new SimilarityComparator(FileUtilities.getName(mediaFile)) {
if (videos.size() > 0) {
videos.sort(new SimilarityComparator(FileUtilities.getName(mediaFile)) {
@Override
public int compare(Object o1, Object o2) {
return super.compare(FileUtilities.getName((File) o1), FileUtilities.getName((File) o2));
}
});
return videos[0];
return videos.get(0);
}
}

View File

@ -1,7 +1,5 @@
package net.filebot.hash;
import static net.filebot.util.FileUtilities.*;
import java.io.File;
@ -12,51 +10,45 @@ import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public final class VerificationUtilities {
/**
* A {@link Pattern} that will match checksums enclosed in brackets ("[]" or "()"). A
* checksum string is a hex number with at least 8 digits. Capturing group 0 will contain
* the matched checksum string.
* A {@link Pattern} that will match checksums enclosed in brackets ("[]" or "()"). A checksum string is a hex number with at least 8 digits. Capturing group 0 will contain the matched checksum string.
*/
public static final Pattern EMBEDDED_CHECKSUM = Pattern.compile("(?<=\\[|\\()(\\p{XDigit}{8})(?=\\]|\\))");
public static String getEmbeddedChecksum(CharSequence string) {
Matcher matcher = EMBEDDED_CHECKSUM.matcher(string);
String embeddedChecksum = null;
// get last match
while (matcher.find()) {
embeddedChecksum = matcher.group();
}
return embeddedChecksum;
}
public static String getHashFromVerificationFile(File file, HashType type, int maxDepth) throws IOException {
return getHashFromVerificationFile(file.getParentFile(), file, type, 0, maxDepth);
}
private static String getHashFromVerificationFile(File folder, File target, HashType type, int depth, int maxDepth) throws IOException {
// stop if we reached max depth or the file system root
if (folder == null || depth > maxDepth)
return null;
// scan all sfv files in this folder
for (File verificationFile : folder.listFiles(type.getFilter())) {
for (File verificationFile : getChildren(folder, type.getFilter())) {
VerificationFileReader parser = new VerificationFileReader(createTextReader(verificationFile), type.getFormat());
try {
while (parser.hasNext()) {
Entry<File, String> entry = parser.next();
// resolve relative file path
File file = new File(folder, entry.getKey().getPath());
if (target.equals(file)) {
return entry.getValue();
}
@ -65,44 +57,41 @@ public final class VerificationUtilities {
parser.close();
}
}
return getHashFromVerificationFile(folder.getParentFile(), target, type, depth + 1, maxDepth);
}
public static HashType getHashType(File verificationFile) {
for (HashType hashType : HashType.values()) {
if (hashType.getFilter().accept(verificationFile))
return hashType;
}
return null;
}
public static HashType getHashTypeByExtension(String extension) {
for (HashType hashType : HashType.values()) {
if (hashType.getFilter().acceptExtension(extension))
return hashType;
}
return null;
}
public static String computeHash(File file, HashType type) throws IOException, InterruptedException {
Hash hash = type.newHash();
// calculate checksum
InputStream in = new FileInputStream(file);
try {
byte[] buffer = new byte[32 * 1024];
int len = 0;
while ((len = in.read(buffer)) >= 0) {
hash.update(buffer, 0, len);
// make this long-running operation interruptible
if (Thread.interrupted())
throw new InterruptedException();
@ -110,16 +99,15 @@ public final class VerificationUtilities {
} finally {
in.close();
}
return hash.digest();
}
/**
* Dummy constructor to prevent instantiation.
*/
private VerificationUtilities() {
throw new UnsupportedOperationException();
}
}

View File

@ -1103,7 +1103,7 @@ public class MediaDetection {
if (file.isDirectory()) {
nfoFiles.addAll(filter(listFiles(file), NFO_FILES));
} else if (file.getParentFile().isDirectory()) {
addAll(nfoFiles, file.getParentFile().listFiles(NFO_FILES));
nfoFiles.addAll(getChildren(file.getParentFile(), NFO_FILES));
}
// parse ids from nfo files
@ -1135,7 +1135,7 @@ public class MediaDetection {
if (!folder.exists())
continue;
for (File nfo : folder.listFiles(NFO_FILES)) {
for (File nfo : getChildren(folder, NFO_FILES)) {
String text = new String(readFile(nfo), "UTF-8");
for (int imdbid : grepImdbId(text)) {

View File

@ -194,24 +194,18 @@ public class ReleaseInfo {
volumes.add(new File(System.getProperty("user.home")));
// Windows / Linux / Mac system roots
addAll(volumes, File.listRoots());
volumes.addAll(getFileSystemRoots());
if (File.separator.equals("/")) {
// Linux and Mac system root folders
for (File root : File.listRoots()) {
File[] f = root.listFiles(FOLDERS);
if (f != null) {
addAll(volumes, f);
}
for (File root : getFileSystemRoots()) {
volumes.addAll(getChildren(root, FOLDERS));
}
// user-specific media roots
for (File root : getMediaRoots()) {
if (root.isDirectory()) {
File[] f = root.listFiles(FOLDERS);
if (f != null) {
addAll(volumes, f);
}
volumes.addAll(getChildren(root, FOLDERS));
}
}
}

View File

@ -112,10 +112,10 @@ class MovieHashMatcher implements AutoCompleteMatcher {
// collect useful nfo files even if they are not part of the selected fileset
Set<File> effectiveNfoFileSet = new TreeSet<File>(nfoFiles);
for (File dir : mapByFolder(movieFiles).keySet()) {
addAll(effectiveNfoFileSet, dir.listFiles(NFO_FILES));
effectiveNfoFileSet.addAll(getChildren(dir, NFO_FILES));
}
for (File dir : filter(fileset, FOLDERS)) {
addAll(effectiveNfoFileSet, dir.listFiles(NFO_FILES));
effectiveNfoFileSet.addAll(getChildren(dir, NFO_FILES));
}
for (File nfo : effectiveNfoFileSet) {

View File

@ -198,7 +198,7 @@ class ChecksumTableTransferablePolicy extends BackgroundFileTransferablePolicy<C
if (seenLevel == null) {
// folder we have never encountered before
for (File verificationFile : folder.listFiles(MediaTypes.getDefaultFilter("verification"))) {
for (File verificationFile : getChildren(folder, MediaTypes.getDefaultFilter("verification"))) {
HashType hashType = getHashType(verificationFile);
cache.put(verificationFile, importVerificationFile(verificationFile, hashType, verificationFile.getParentFile()));
types.put(verificationFile, hashType);

View File

@ -1,41 +1,42 @@
package net.filebot.ui.transfer;
import java.io.File;
import java.io.FilenameFilter;
import javax.swing.filechooser.FileFilter;
public class TransferablePolicyFileFilter extends FileFilter implements FilenameFilter {
public class TransferablePolicyFileFilter extends FileFilter {
private final TransferablePolicy transferablePolicy;
public TransferablePolicyFileFilter(TransferablePolicy transferablePolicy) {
this.transferablePolicy = transferablePolicy;
}
@Override
public boolean accept(File f) {
if (f.isDirectory())
return true;
try {
return transferablePolicy.accept(new FileTransferable(f));
} catch (Exception e) {
return false;
}
}
@Override
public boolean accept(File dir, String name) {
return accept(new File(dir, name));
}
@Override
public String getDescription() {
if (transferablePolicy instanceof FileTransferablePolicy) {
return ((FileTransferablePolicy) transferablePolicy).getFileFilterDescription();
}
return null;
}
}

View File

@ -415,12 +415,34 @@ public final class FileUtilities {
return f;
}
public static List<File> getChildren(File file) {
File[] files = file.listFiles();
public static List<File> getFileSystemRoots() {
File[] roots = File.listRoots();
// roots array may be null if folder permissions do not allow listing of files
if (roots == null) {
roots = new File[0];
}
return asList(roots);
}
public static List<File> getChildren(File folder) {
File[] files = folder.listFiles();
// children array may be null if folder permissions do not allow listing of files
if (files == null) {
return asList(new File[0]);
files = new File[0];
}
return asList(files);
}
public static List<File> getChildren(File folder, FileFilter filter) {
File[] files = folder.listFiles(filter);
// children array may be null if folder permissions do not allow listing of files
if (files == null) {
files = new File[0];
}
return asList(files);