9a94047bf2b4de8c9740d203134527ddf749db48
[vamsas.git] / src / uk / ac / vamsas / client / VorbaXmlBinder.java
1 /**
2  * 
3  */
4 package uk.ac.vamsas.client;
5
6 import java.io.IOException;
7 import java.io.PrintWriter;
8 import java.io.Reader;
9 import java.io.Writer;
10 import java.lang.reflect.Field;
11 import java.util.Hashtable;
12 import java.util.Iterator;
13 import java.util.Vector;
14
15 import org.apache.commons.logging.Log;
16 import org.apache.commons.logging.LogFactory;
17 import org.exolab.castor.mapping.FieldHandler;
18 import org.exolab.castor.mapping.GeneralizedFieldHandler;
19 import org.exolab.castor.mapping.ValidityException;
20 import org.exolab.castor.xml.IDResolver;
21 import org.exolab.castor.xml.MarshalException;
22 import org.exolab.castor.xml.MarshalListener;
23 import org.exolab.castor.xml.Marshaller;
24 import org.exolab.castor.xml.UnmarshalListener;
25 import org.exolab.castor.xml.Unmarshaller;
26 import org.exolab.castor.xml.ValidationException;
27
28 import uk.ac.vamsas.objects.core.VamsasDocument;
29 /**
30  * Implements the Vamsas Vobject ID machinery for translating 
31  * between non-volatile XML IDs and Vobject references. Use the
32  * marshalling and unmarshalling methods in this class in order
33  * to add automatically computed values for required fields in objects,
34  * so as to avoid validation exceptions when marshalling new objects
35  * into the vamsas document.
36  */
37 public class VorbaXmlBinder implements UnmarshalListener {
38   private static Log log = LogFactory.getLog(VorbaXmlBinder.class);
39   private final IVorbaIdFactory vorbafactory;
40
41   private final Vector obj;
42   private final Hashtable oldobjhashes;
43   private final Hashtable objrefs;
44   private final Vector updatedobjs;
45
46   public VorbaXmlBinder(IVorbaIdFactory vorbafactory, Vector obj, Hashtable objrefs, Hashtable oldobjhashes, Vector updatedobjs) {
47     this.vorbafactory = vorbafactory;
48     this.obj = obj;
49     this.objrefs = objrefs;
50     this.oldobjhashes = oldobjhashes;
51     this.updatedobjs = updatedobjs;
52   }
53
54   /*
55    * (non-Javadoc)
56    * 
57    * @see org.exolab.castor.xml.UnmarshalListener#attributesProcessed(java.lang.Object)
58    */
59   public void attributesProcessed(Object object) {
60   }
61
62   /*
63    * (non-Javadoc)
64    * 
65    * @see org.exolab.castor.xml.UnmarshalListener#fieldAdded(java.lang.String,
66    *      java.lang.Object, java.lang.Object)
67    */
68   public void fieldAdded(String fieldName, Object parent, Object child) {
69     if (parent instanceof Vobject && child instanceof Vobject) {
70       if (((Vobject) child).V_parent==null) {
71         // System.err.println("Setting parent of "+fieldName);
72         ((Vobject) child).setV_parent((Vobject) parent);
73       }
74     }
75   }
76
77   /*
78    * (non-Javadoc)
79    * 
80    * @see org.exolab.castor.xml.UnmarshalListener#initialized(java.lang.Object)
81    */
82   public void initialized(Object object) {
83   }
84
85   /*
86    * Check if the object has an 'id' field - if it does, copy the value into
87    * the VorbaId field of Vobject, and add the Vobject to the VorbaId hash.
88    * 
89    * @see org.exolab.castor.xml.UnmarshalListener#unmarshalled(java.lang.Object)
90    */
91   public void unmarshalled(Object newobj) {
92     if (newobj instanceof Vobject) {
93       Vobject nobj = (Vobject) newobj;
94       nobj.set__stored_in_document(true);
95       try {
96         if (nobj.isRegisterable() && nobj.___id_field!=null) {
97           VorbaId nobj_id=null;
98           // look for the id field (should be an NCName string)
99           nobj.__vorba = vorbafactory;
100           // use the Vobject accessor method to avoid unpleasant security exceptions.
101           String idstring = nobj.__getInstanceIdField();
102           if (idstring!=null) { 
103             if (idstring.length() > 0) {
104               nobj.setVorbaId(VorbaId.newId(idstring));
105               nobj_id=nobj.getVorbaId();
106               if (objrefs.containsKey(nobj_id) && !objrefs.get(nobj_id).equals(nobj)) {
107                 System.err.println("Serious problem : duplicate id '"+idstring+"' found! expect badness.");
108                 // TODO: HANDLE duplicate XML ids correctly
109               }
110               objrefs.put(nobj_id, nobj);
111             } else {
112               // add to list of objects without a valid vorbaId
113               obj.add(nobj);
114             }
115           } else {
116             // TODO: add to list of objects without a valid vorbaId
117             obj.add(nobj);
118           }
119           nobj.doHash();
120           // check to see if new object was present in old object hash
121           if (nobj_id!=null) {
122             if (oldobjhashes.containsKey(nobj_id)) {
123               Vobjhash oldhash = (Vobjhash) oldobjhashes.get(nobj_id);
124               if (oldhash.isUpdated(nobj)) {
125                 // mark the object as updated in this document read.
126                 nobj.set__updated_since_last_read(true);
127                 oldobjhashes.put(nobj_id, new Vobjhash(nobj));
128                 updatedobjs.addElement(nobj);
129               }
130             } else {
131               // object has no entry in the oldhashvalue list but
132               // there is a valid vorbaId so
133               nobj.set__added_since_last_read(true);
134
135             }
136             // and record the just-unmarshalled hash value
137             oldobjhashes.put(nobj_id, new Vobjhash(nobj));
138           } else {
139             // for objects yet to get a valid vorba_id
140             nobj.set__added_since_last_read(true);
141           }
142         }
143
144       } catch (Exception e) {
145         return;
146       };
147
148     }
149   }
150
151   /**
152    * writes the VamsasDocument to the given stream.
153    * TODO: ensure that (at least) default provenance entries are written for objects.
154    * @param outstream
155    * @param vorba valid VorbaIdFactory to construct any missing IDs 
156    * @param doc
157    * @throws IOException
158    * @throws MarshalException
159    * @throws ValidationException
160    */
161   public static void putVamsasDocument(PrintWriter outstream, VorbaIdFactory vorba, VamsasDocument doc)
162   throws IOException, MarshalException, ValidationException {
163     // Ensure references
164     if (vorba==null)
165       throw new Error("Null VorbaIdFactory Parameter");
166     if (doc.__vorba==null)
167       doc.__vorba = vorba;
168     doc.__ensure_instance_ids(); // this may take a while. Do we allow for cyclic references ? 
169     doc.marshal(outstream);
170
171   }
172   /**
173    * creates new VorbaId references where necessary for newly unmarshalled objects
174    * @param unrefed
175    * @param objrefs
176    * @return false if any new object references were made
177    */
178   private static boolean ensure_references(Vector unrefed, Hashtable objrefs) {
179     boolean sync=true;
180     if (unrefed.size()>0) {
181       sync=false; // document is out of sync - ids have been created.
182       java.util.Iterator newobj = unrefed.listIterator();
183       while (newobj.hasNext()) {
184         Vobject o = (Vobject) newobj.next();
185         // forces registration and id field update.
186         VorbaId id = o.getVorbaId();
187         if (!objrefs.containsKey(id)) {
188           objrefs.put(id, o);
189         } else {
190           if (!objrefs.get(id).equals(o))
191             throw new Error("Serious! Duplicate reference made by vorbaIdFactory!");
192         }
193       }
194     }
195     return sync;
196   }
197   /**
198    * Unmarshals a vamsasDocument Vobject from a stream, registers
199    * unregistered objects, records existing VorbaIds, and completes 
200    * the uk.ac.vamsas.client.Vobject housekeeping fields.
201    * For a valid unmarshalling, the array of returned objects also includes
202    * a <return>sync</return> parameter which is true if new VorbaIds
203    * were created. If sync is false, then the caller should ensure that the
204    * vamsasDocument is written back to disk to propagate the new VorbaIds.
205    *  TODO: ensure that provenance is correct for newly registered objects
206    * as getVamsasObjects but will detect updated objects based on differing hash values
207    * obtained from the VorbaIdFactory's VorbaId, Vobject.get__last_Hash() pairs (if any) 
208    * @param instream - the XML input stream 
209    * @param factory - the SimpleClient's properly configured VorbaId factory to make new references.
210    * @param root the root element's uk.ac.vamsas.objects.core Vobject.
211    * @return null or {(Object) VamsasDocument Vobject, (Object) Hashtable of Vobject references, (Object) Boolean(sync), (Object) Vector of updated objects in document }
212    */
213   public static Object[] getVamsasObjects(Reader instream,
214       VorbaIdFactory factory, Vobject root) {  
215     Unmarshaller unmarshaller = new Unmarshaller(root);
216     unmarshaller.setIDResolver(new IDResolver() {
217       public Object resolve(String id) {
218         VorbaXmlBinder.log.warn("Warning - id " + id
219             + " is not found in the Vamsas XML!");
220         return null;
221       }
222     });
223     final Hashtable objrefs = new Hashtable();
224     if (factory.extanthashv==null)
225       factory.extanthashv=new Hashtable();
226     final Hashtable oobjhashes=factory.extanthashv;
227     final VorbaIdFactory vorbafactory = factory;
228     final Vector unrefedObj =  new Vector();
229     final Vector updatedObj = new Vector();
230     unmarshaller.setUnmarshalListener(new VorbaXmlBinder(vorbafactory, unrefedObj, objrefs, oobjhashes, updatedObj));
231     // Call the unmarshaller.
232     try {
233       while (instream.ready()) {
234         // TODO: mark objects in oobjhash prior to unmarshalling, to detect when objects have been lost through an update.
235         //tohere
236         Object obj = unmarshaller.unmarshal(instream);
237         boolean sync=ensure_references(unrefedObj, objrefs);
238         if (!(obj instanceof Vobject))
239           return null;
240         vorbafactory.setNewIdHash(objrefs); // update the Document IO Handler's set of vorbaId<>Object bindings.
241         return new Object[] { obj, objrefs, new Boolean(sync),updatedObj};
242       }
243     } catch (MarshalException e) {
244       // TODO Auto-generated catch block
245       e.printStackTrace();
246     } catch (ValidationException e) {
247       // TODO Auto-generated catch block
248       e.printStackTrace();
249     } catch (IOException e) {
250       // TODO Auto-generated catch block
251       e.printStackTrace();
252     }
253     return null;
254   }
255 }