filebot/source/net/filebot/hash/VerificationFileReader.java

107 lines
1.9 KiB
Java
Raw Normal View History

2014-04-19 02:30:29 -04:00
package net.filebot.hash;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.Iterator;
2013-09-11 13:22:00 -04:00
import java.util.Map.Entry;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
public class VerificationFileReader implements Iterator<Entry<File, String>>, Closeable {
2015-07-25 18:47:19 -04:00
private final Scanner scanner;
2015-07-25 18:47:19 -04:00
private final VerificationFormat format;
2015-07-25 18:47:19 -04:00
private Entry<File, String> buffer;
2015-07-25 18:47:19 -04:00
private int lineNumber = 0;
2015-07-25 18:47:19 -04:00
public VerificationFileReader(Readable source, VerificationFormat format) {
this.scanner = new Scanner(source);
this.format = format;
}
2015-07-25 18:47:19 -04:00
@Override
public boolean hasNext() {
if (buffer == null) {
// cache next entry
buffer = nextEntry();
}
2015-07-25 18:47:19 -04:00
return buffer != null;
}
2015-07-25 18:47:19 -04:00
@Override
public Entry<File, String> next() {
// cache next entry
if (!hasNext()) {
throw new NoSuchElementException();
}
2015-07-25 18:47:19 -04:00
try {
return buffer;
} finally {
// invalidate cache
buffer = null;
}
}
2015-07-25 18:47:19 -04:00
protected Entry<File, String> nextEntry() {
Entry<File, String> entry = null;
2015-07-25 18:47:19 -04:00
// get next valid entry
while (entry == null && scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
2015-07-25 18:47:19 -04:00
// ignore comments
if (!isComment(line)) {
try {
entry = format.parseObject(line);
} catch (ParseException e) {
// log and ignore
Logger.getLogger(getClass().getName()).log(Level.WARNING, String.format("Illegal format on line %d: %s", lineNumber, line));
}
}
2015-07-25 18:47:19 -04:00
lineNumber++;
}
2015-07-25 18:47:19 -04:00
return entry;
}
2015-07-25 18:47:19 -04:00
public int getLineNumber() {
return lineNumber;
}
2015-07-25 18:47:19 -04:00
protected boolean isComment(String line) {
2009-04-05 05:31:02 -04:00
return line.isEmpty() || line.startsWith(";");
}
2015-07-25 18:47:19 -04:00
@Override
public void close() throws IOException {
scanner.close();
}
2015-07-25 18:47:19 -04:00
@Override
public void remove() {
throw new UnsupportedOperationException();
}
2015-07-25 18:47:19 -04:00
}