/* JFox, the OpenSource J2EE Application Server
 *
 * Copyright (C) 2002 huihoo.com
 * Distributable under GNU LGPL license
 * See the GNU Lesser General Public License for more details.
 */

package org.huihoo.jfox.persistent;

import java.io.Serializable;
import java.io.NotSerializableException;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.FileInputStream;
import java.util.Date;
import javax.management.ObjectName;
import javax.management.MalformedObjectNameException;

/**
 * 
 * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
 */

public class FilePersistenter extends Persistenter {

  public static ObjectName DEFAULT_OBJECTNAME = null;

  static {
    try{
      DEFAULT_OBJECTNAME = new ObjectName(":Service=FilePersistenter");
    }
    catch(MalformedObjectNameException e){
      e.printStackTrace();
    }
  };

  public FilePersistenter() {

  }

  public synchronized Object load(Object identity) throws Exception {
    if(identity == null) throw new IllegalArgumentException("identity can not be null.");

    Object result = null;
    ObjectInputStream ois = null;
    try{
      String filename = identity.toString();
      ois = new ObjectInputStream(new FileInputStream(filename));
      result = ois.readObject();
    }
    finally {
      try{
        ois.close();
      }
      catch(IOException e){ }
    }

    return result;
  }

  // identity is the filename
  public synchronized void store(Object identity, Object data) throws Exception {
    if(identity == null || data == null) throw new IllegalArgumentException("identity and data can not be null.");
    if(!(data instanceof Serializable)) throw new NotSerializableException(data.getClass().getName() + " must implement java.io.Serializable");
    String filename = identity.toString();
    if(filename.indexOf(':') >= 0){
      throw new IOException("can not doCreate file \"" + filename + "\" to store object " + data.toString());
    }
    ObjectOutputStream oos = null;
    try {
      oos = new ObjectOutputStream(new FileOutputStream(filename));
      oos.writeObject(data);
    }
    catch(Exception e){
      throw e;
    }
    finally {
      try{
        oos.close();
      }
      catch(IOException e){
        e.printStackTrace();
      }
    }
  }

	public static void main(String[] args) throws Exception {
    Date date = new Date();
    FilePersistenter fp = new FilePersistenter();
    String identity = "fp.ser";
    fp.store(identity,date);
    Date serDate = (Date)fp.load(identity);
    System.out.println(serDate.toString());
	}

}
