refactoring org to uk
[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               if (objrefs.containsKey(nobj_id=nobj.getVorbaId()) && !objrefs.get(nobj.getVorbaId()).equals(nobj)) {
106                 System.err.println("Serious problem : duplicate id '"+idstring+"' found! expect badness.");
107                 // TODO: HANDLE duplicate XML ids correctly
108               }
109               objrefs.put(nobj_id, nobj);
110             } else {
111               // add to list of objects without a valid vorbaId
112               obj.add(nobj);
113             }
114           } else {
115             // TODO: add to list of objects without a valid vorbaId
116             obj.add(nobj);
117           }
118           
119         nobj.doHash();
120         // check to see if new object was present in old object hash
121         if (oldobjhashes.containsKey(nobj.getVorbaId())) {
122           Vobjhash oldhash = (Vobjhash) oldobjhashes.get(nobj.getVorbaId());
123           if (oldhash.isUpdated(nobj)) {
124             // mark the object as updated in this document read.
125             nobj.set__updated_since_last_read(true);
126             oldobjhashes.put(nobj_id, new Vobjhash(nobj));
127             updatedobjs.addElement(nobj);
128           }
129         }
130       }
131       } catch (Exception e) {
132         return;
133       };
134       
135     }
136   }
137
138   /**
139    * writes the VamsasDocument to the given stream.
140    * TODO: ensure that (at least) default provenance entries are written for objects.
141    * @param outstream
142    * @param vorba valid VorbaIdFactory to construct any missing IDs 
143    * @param doc
144    * @throws IOException
145    * @throws MarshalException
146    * @throws ValidationException
147    */
148   public static void putVamsasDocument(PrintWriter outstream, VorbaIdFactory vorba, VamsasDocument doc)
149       throws IOException, MarshalException, ValidationException {
150     // Ensure references
151     if (vorba==null)
152       throw new Error("Null VorbaIdFactory Parameter");
153     if (doc.__vorba==null)
154       doc.__vorba = vorba;
155     doc.__ensure_instance_ids(); // this may take a while. Do we allow for cyclic references ? 
156     doc.marshal(outstream);
157     
158   }
159   /**
160    * creates new VorbaId references where necessary for newly unmarshalled objects
161    * @param unrefed
162    * @param objrefs
163    * @return false if any new object references were made
164    */
165   private static boolean ensure_references(Vector unrefed, Hashtable objrefs) {
166     boolean sync=true;
167     if (unrefed.size()>0) {
168       sync=false; // document is out of sync - ids have been created.
169       java.util.Iterator newobj = unrefed.listIterator();
170       while (newobj.hasNext()) {
171         Vobject o = (Vobject) newobj.next();
172         // forces registration and id field update.
173         VorbaId id = o.getVorbaId();
174         if (!objrefs.containsKey(id)) {
175           objrefs.put(id, o);
176         } else {
177           if (!objrefs.get(id).equals(o))
178             throw new Error("Serious! Duplicate reference made by vorbaIdFactory!");
179         }
180       }
181     }
182     return sync;
183   }
184   /**
185      * Unmarshals a vamsasDocument Vobject from a stream, registers
186      * unregistered objects, records existing VorbaIds, and completes 
187      * the uk.ac.vamsas.client.Vobject housekeeping fields.
188      * For a valid unmarshalling, the array of returned objects also includes
189      * a <return>sync</return> parameter which is true if new VorbaIds
190      * were created. If sync is false, then the caller should ensure that the
191      * vamsasDocument is written back to disk to propagate the new VorbaIds.
192      *  TODO: ensure that provenance is correct for newly registered objects
193      * as getVamsasObjects but will detect updated objects based on differing hash values
194      * obtained from the VorbaIdFactory's VorbaId, Vobject.get__last_Hash() pairs (if any) 
195      * @param instream - the XML input stream 
196    * @param factory - the SimpleClient's properly configured VorbaId factory to make new references.
197    * @param root the root element's uk.ac.vamsas.objects.core Vobject.
198      * @return null or {(Object) VamsasDocument Vobject, (Object) Hashtable of Vobject references, (Object) Boolean(sync), (Object) Vector of updated objects in document }
199      */
200   public static Object[] getVamsasObjects(Reader instream,
201         VorbaIdFactory factory, Vobject root) {  
202     Unmarshaller unmarshaller = new Unmarshaller(root);
203       unmarshaller.setIDResolver(new IDResolver() {
204         public Object resolve(String id) {
205           VorbaXmlBinder.log.warn("Warning - id " + id
206               + " is not found in the Vamsas XML!");
207           return null;
208         }
209       });
210       final Hashtable objrefs = new Hashtable();
211       if (factory.extanthashv==null)
212         factory.extanthashv=new Hashtable();
213       final Hashtable oobjhashes=factory.extanthashv;
214       final VorbaIdFactory vorbafactory = factory;
215       final Vector unrefedObj =  new Vector();
216       final Vector updatedObj = new Vector();
217       unmarshaller.setUnmarshalListener(new VorbaXmlBinder(vorbafactory, unrefedObj, objrefs, oobjhashes, updatedObj));
218       // Call the unmarshaller.
219       try {
220         while (instream.ready()) {
221           // TODO: mark objects in oobjhash prior to unmarshalling, to detect when objects have been lost through an update.
222           //tohere
223           Object obj = unmarshaller.unmarshal(instream);
224           boolean sync=ensure_references(unrefedObj, objrefs);
225           if (!(obj instanceof Vobject))
226             return null;
227           vorbafactory.setNewIdHash(objrefs); // update the Document IO Handler's set of vorbaId<>Object bindings.
228           return new Object[] { obj, objrefs, new Boolean(sync),updatedObj};
229           }
230       } catch (MarshalException e) {
231         // TODO Auto-generated catch block
232         e.printStackTrace();
233       } catch (ValidationException e) {
234         // TODO Auto-generated catch block
235         e.printStackTrace();
236       } catch (IOException e) {
237         // TODO Auto-generated catch block
238         e.printStackTrace();
239       }
240       return null;
241     }
242 }