package org.prevayler.implementation;
import java.io.EOFException;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.util.Arrays;
class NumberFileFinder {
private File directory;
private File lastSnapshot;
private long fileNumber;
private NumberFileCreator fileCreator;
public NumberFileFinder(String directoryName) throws IOException {
this.directory = new File(directoryName);
if (!directory.exists() && !directory.mkdirs()) throw new IOException("Directory doesn't exist and could not be created: " + directoryName);
if (!directory.isDirectory()) throw new IllegalArgumentException("Path exists but is not a directory: " + directoryName);
System.out.println("Directory for Prevayler is: " + directory.getAbsolutePath());
init();
}
public File lastSnapshot() {
return lastSnapshot;
}
public File nextPendingLog() throws EOFException {
File log = new File(directory, NumberFileCreator.LOG_FORMAT.format(fileNumber + 1));
if (!log.exists()) {
fileCreator = new NumberFileCreator(directory, fileNumber + 1);
throw new EOFException();
}
++fileNumber;
return log;
}
public NumberFileCreator fileCreator() {
return fileCreator;
}
private void init() throws IOException {
findLastSnapshot();
fileNumber = lastSnapshot == null
? 0
: number(lastSnapshot);
}
private long number(File snapshot) throws NumberFormatException { String name = snapshot.getName();
if (!name.endsWith("." + NumberFileCreator.SNAPSHOT_SUFFIX)) throw new NumberFormatException();
return Long.parseLong(name.substring(0,name.indexOf('.'))); }
private void findLastSnapshot() throws IOException {
File[] snapshots = directory.listFiles(new SnapshotFilter());
if (snapshots == null) throw new IOException("Error reading file list from directory " + directory);
Arrays.sort(snapshots);
lastSnapshot = snapshots.length > 0
? snapshots[snapshots.length - 1]
: null;
}
private class SnapshotFilter implements FileFilter {
public boolean accept(File file) {
try {
number(file);
} catch (NumberFormatException nfx) {
return false;
}
return true;
}
}
}