1 /*
2  * @(#) $Id: DefaultBankPersistenceManager.java,v 1.2 2003/07/08 08:13:53 pankaj Exp $
3  *
4  * Copyright (c) 2002-03 by Pankaj Kumar (http://www.pankaj-k.net). 
5  * All rights reserved.
6  *
7  * The license governing the use of this file can be found in the 
8  * root directory of the containing software.
9  */
10package org.jstk.example.bank.server;
11
12import org.jstk.example.bank.*;
13import java.util.Iterator;
14import java.util.Properties;
15import java.io.*;
16
17import java.security.*;
18
19public class DefaultBankPersistenceManager implements BankPersistenceManagerIntf {
20    private Bank bank;
21    private String filename;
22    private boolean noPersistence = false;
23
24    public DefaultBankPersistenceManager(Properties props){
25        this.filename = props.getProperty("org.jstk.example.bank.file");
26        if (filename == null)
27            noPersistence = true;
28    }
29    public void save(){
30        if (noPersistence)
31            return;
32
33        ObjectOutputStream oos;
34        try {
35            oos = new ObjectOutputStream(new FileOutputStream(filename));
36            oos.writeObject(bank);
37            oos.flush();
38            oos.close();
39        } catch (IOException ioe){
40            System.err.println("writeObject failed: " + ioe);
41            noPersistence = true;
42        }
43    }
44    public BankIntf load() throws Exception {
45        if (noPersistence){
46            bank = new Bank();
47        } else {
48            ObjectInputStream ois = null;
49            bank = null;
50            try {
51                ois = new ObjectInputStream(new FileInputStream(filename));
52                bank = (Bank)ois.readObject();
53            } catch (FileNotFoundException fnfe){
54                bank = new Bank();
55            } catch (IOException ioe){
56                System.err.println("Error: reading Bank data from file \"" + filename + "\"");
57                System.err.println("Initializing a fresh one.");
58                bank = new Bank();
59            }
60        }
61
62        bank.setPersistenceManager(this);
63        Iterator itr = bank._accounts();
64        while (itr.hasNext()){
65            Account acct = (Account)itr.next();
66            acct.setPersistenceManager(this);
67        }
68        return bank;
69    }
70}