001: /* JFox, the OpenSource J2EE Application Server
002: *
003: * Copyright (C) 2002 huihoo.com
004: * Distributable under GNU LGPL license
005: * See the GNU Lesser General Public License for more details.
006: */
007:
008: package org.huihoo.jfox.persistent;
009:
010: import java.io.Serializable;
011: import java.io.NotSerializableException;
012: import java.io.FileOutputStream;
013: import java.io.ObjectOutputStream;
014: import java.io.IOException;
015: import java.io.ObjectInputStream;
016: import java.io.FileInputStream;
017: import java.util.Date;
018: import javax.management.ObjectName;
019: import javax.management.MalformedObjectNameException;
020:
021: /**
022: *
023: * @author <a href="mailto:young_yy@hotmail.com">Young Yang</a>
024: */
025:
026: public class FilePersistenter extends Persistenter {
027:
028: public static ObjectName DEFAULT_OBJECTNAME = null;
029:
030: static {
031: try {
032: DEFAULT_OBJECTNAME = new ObjectName(
033: ":Service=FilePersistenter");
034: } catch (MalformedObjectNameException e) {
035: e.printStackTrace();
036: }
037: };
038:
039: public FilePersistenter() {
040:
041: }
042:
043: public synchronized Object load(Object identity) throws Exception {
044: if (identity == null)
045: throw new IllegalArgumentException(
046: "identity can not be null.");
047:
048: Object result = null;
049: ObjectInputStream ois = null;
050: try {
051: String filename = identity.toString();
052: ois = new ObjectInputStream(new FileInputStream(filename));
053: result = ois.readObject();
054: } finally {
055: try {
056: ois.close();
057: } catch (IOException e) {
058: }
059: }
060:
061: return result;
062: }
063:
064: // identity is the filename
065: public synchronized void store(Object identity, Object data)
066: throws Exception {
067: if (identity == null || data == null)
068: throw new IllegalArgumentException(
069: "identity and data can not be null.");
070: if (!(data instanceof Serializable))
071: throw new NotSerializableException(data.getClass()
072: .getName()
073: + " must implement java.io.Serializable");
074: String filename = identity.toString();
075: if (filename.indexOf(':') >= 0) {
076: throw new IOException("can not doCreate file \"" + filename
077: + "\" to store object " + data.toString());
078: }
079: ObjectOutputStream oos = null;
080: try {
081: oos = new ObjectOutputStream(new FileOutputStream(filename));
082: oos.writeObject(data);
083: } catch (Exception e) {
084: throw e;
085: } finally {
086: try {
087: oos.close();
088: } catch (IOException e) {
089: e.printStackTrace();
090: }
091: }
092: }
093:
094: public static void main(String[] args) throws Exception {
095: Date date = new Date();
096: FilePersistenter fp = new FilePersistenter();
097: String identity = "fp.ser";
098: fp.store(identity, date);
099: Date serDate = (Date) fp.load(identity);
100: System.out.println(serDate.toString());
101: }
102:
103: }
|