// Copyright 1997, MageLang Institute. import java.io.*; import java.util.Date; import java.util.Vector; import java.util.Enumeration; class TreeNode implements Serializable, ObjectInputValidation { Vector children; TreeNode parent; String name; /* the timeStamp will mark when this object is instantiated or read from a stream */ transient Date timeStamp; /* the magic number will keep track of how often this object is read in from a stream */ transient int magicNumber = 0; public TreeNode(String s) { children = new Vector(5); name = s; timeStamp = new Date(); } public void addChild(TreeNode n) { children.addElement(n); n.parent = this; } private void writeObject(ObjectOutputStream stream) throws IOException { try { stream.defaultWriteObject(); stream.writeInt(magicNumber); } catch(Exception e) { System.out.println(e); } } private void readObject(ObjectInputStream stream) throws IOException { try { stream.registerValidation(this,0); stream.defaultReadObject(); magicNumber = stream.readInt() + 1; timeStamp = new Date(); } catch(Exception e) { System.out.println(e); } } /** check that each child has this object as it's parent */ public void validateObject() throws InvalidObjectException { Enumeration e = children.elements(); while(e.hasMoreElements()) { if(((TreeNode)e.nextElement()).parent != this) throw new InvalidObjectException(getClass().getName()); } } public String toString() { Enumeration e = children.elements(); StringBuffer buff = new StringBuffer(100); buff.append("[ " + name + "(magicNum:" + magicNumber + ")(tStamp:" + timeStamp + ") : "); while(e.hasMoreElements()) { buff.append(e.nextElement().toString()); } buff.append(" ] "); return buff.toString(); } } public class ValidateTest { public static void main(String[] args) { // first build a tree TreeNode top = new TreeNode("top"); top.addChild(new TreeNode("left")); top.addChild(new TreeNode("right")); // print it out to see how it looks System.out.println("source tree: \n" + top.toString()); // now write the tree to a file, and read it back in again try { FileOutputStream fOut = new FileOutputStream("test.out"); ObjectOutput out = new ObjectOutputStream(fOut); out.writeObject(top); out.flush(); out.close(); FileInputStream fIn = new FileInputStream("test.out"); ObjectInputStream in = new ObjectInputStream(fIn); TreeNode n = (TreeNode)in.readObject(); in.close(); System.out.println("read tree: \n" + n.toString()); } catch (Exception e) { System.out.println("exception: " + e); } } }