/*
 * @(#)Saver.java
 *
 * Copyright 2001 Thomas P. Hayes, All Rights Reserved.
 *
 * This software is the proprietary information of Thomas P. Hayes.
 * Use outside the CSPP 535 course taught by the author is subject
 * to license agreement.
 */

package saveopen.application;
import javax.swing.*;
import java.awt.event.*;
import java.io.*;

/**
 * This class provides two static methods, 
 * <code>save()</code> and <code>open()</code>.  
 * Since this is all, the class has been declared <code>final</code>,
 * so that it cannot be instantiated (which would serve no purpose).
 */ 
public final class Saver {
    
    /**
     * Saves a given Serializable component into a file with the
     * given name.
     */
    public static void save(Serializable target, String filename) {
        System.out.println("Saver.save invoked.");
        System.out.println(target);
        try {
            FileOutputStream out = new FileOutputStream(filename);
            ObjectOutputStream s = new ObjectOutputStream(out);
            s.writeObject(target);
            s.flush();
            s.close();
        } catch (Exception ex) {System.out.println("Save exception.");
        ex.printStackTrace();}
        System.out.println("Saver.save finished.");
    }
    
    /**
     * Retrieves the Serializable component in the file with the
     * given name.
     */
    public static Object open(String filename) {
        System.out.println("Saver.open invoked.");
        try {
            FileInputStream in = new FileInputStream(filename);
            ObjectInputStream s = new ObjectInputStream(in);
            Object restoredObject = s.readObject();
            s.close();
            return restoredObject;
        } catch (Exception ex) {
	    System.out.println("Exception in Open.");
	    ex.printStackTrace();
	    System.out.println("Saver.open finished.");
	    return null;
	}
    }

    public static Object openAndRun(String filename) {
        System.out.println("Saver.openAndRun invoked.");
        try {
            FileInputStream in = new FileInputStream(filename);
            ObjectInputStream s = new ObjectInputStream(in);
            Object restoredObject = s.readObject();
            s.close();
	    ((Runnable)restoredObject).run();
            return restoredObject;
        } catch (Exception ex) {
	    System.out.println("Exception in OpenAndRun.");
	    ex.printStackTrace();
	    System.out.println("Saver.openAndRun finished.");
	    return null;
	}
    }

}





