- import java.io.*;
- public class PrevaylerJr {
- public static interface Command extends Serializable {
- Object executeOn(Object system);
- }
- private final Object _system;
- private final ObjectOutputStream _journal;
- public PrevaylerJr(Serializable initialState, File storageFile) throws Exception {
- File tempFile = new File(storageFile.getAbsolutePath() + ".tmp");
- _system = restoreState(initialState, storageFile, tempFile);
- _journal = new ObjectOutputStream(new FileOutputStream(tempFile));
- writeToJournal(_system);
- if (storageFile.delete() && tempFile.renameTo(storageFile))
- return;
- throw new IOException("Unable to rename " + tempFile + " to " + storageFile);
- }
- synchronized
- public Object executeTransaction(Command transaction) throws Exception {
- writeToJournal(transaction);
- return transaction.executeOn(_system);
- }
- synchronized
- public Object executeQuery(Command query) {
- return query.executeOn(_system);
- }
- private Object restoreState(Object initialState, File storageFile, File tempFile) {
- Object state = initialState;
- try {
- File fileToRead = storageFile.exists() ? storageFile : tempFile;
- ObjectInputStream input = new ObjectInputStream(new FileInputStream(fileToRead));
- state = restoreImage(input);
- restoreCommands(state, input);
- } catch (Exception endOfStreamReached) {}
- return state;
- }
- private Serializable restoreImage(ObjectInputStream input) throws IOException, ClassNotFoundException {
- return (Serializable) input.readObject();
- }
- private void restoreCommands(Object state, ObjectInputStream input) throws IOException, ClassNotFoundException {
- while (true)
- ((Command) input.readObject()).executeOn(state);
- }
- private void writeToJournal(Object object) throws IOException {
- _journal.writeObject(object);
- _journal.flush();
- }
- }