Skip to content

Instantly share code, notes, and snippets.

@skiwi2
Created January 7, 2015 21:10
Show Gist options
  • Save skiwi2/30f2afe29e53cb13f74f to your computer and use it in GitHub Desktop.
Save skiwi2/30f2afe29e53cb13f74f to your computer and use it in GitHub Desktop.
package com.skiwi.hearthmonitor.logreader;
import com.skiwi.hearthmonitor.logapi.LogEntry;
import java.util.*;
/**
* @author Frank van Heeswijk
*/
public abstract class AbstractLogReader implements LogReader {
private final Set<EntryReader> entryReaders = entryReaders();
private final Deque<String> linesInMemory = new ArrayDeque<>();
@Override
public LogEntry readEntry() throws NotReadableException {
String line = readLineInternal();
for (EntryReader entryReader : entryReaders) {
if (!entryReader.isParsable(line)) {
continue;
}
try {
return entryReader.parse(line, this::readLineInternal);
} catch (NotParsableException ex) {
List<String> notReadableLines = new ArrayList<>();
while (!linesInMemory.isEmpty()) {
notReadableLines.add(linesInMemory.pop());
}
throw new NotReadableException(notReadableLines);
}
}
throw new IllegalStateException();
}
//TODO throw exception if modified after construction
abstract protected Set<EntryReader> entryReaders();
abstract protected String readLineFromLog();
private String readLineInternal() {
if (!linesInMemory.isEmpty()) {
return linesInMemory.pop();
}
String line = readLineFromLog();
linesInMemory.push(line);
return line;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment