4 package uk.ac.vamsas.client;
6 import java.io.IOException;
7 import java.io.PrintWriter;
10 import java.lang.reflect.Field;
11 import java.util.Hashtable;
12 import java.util.Iterator;
13 import java.util.Vector;
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;
28 import uk.ac.vamsas.objects.core.VamsasDocument;
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.
37 public class VorbaXmlBinder implements UnmarshalListener {
38 private static Log log = LogFactory.getLog(VorbaXmlBinder.class);
39 private final IVorbaIdFactory vorbafactory;
41 private final Vector obj;
42 private final Hashtable oldobjhashes;
43 private final Hashtable objrefs;
44 private final Vector updatedobjs;
46 public VorbaXmlBinder(IVorbaIdFactory vorbafactory, Vector obj, Hashtable objrefs, Hashtable oldobjhashes, Vector updatedobjs) {
47 this.vorbafactory = vorbafactory;
49 this.objrefs = objrefs;
50 this.oldobjhashes = oldobjhashes;
51 this.updatedobjs = updatedobjs;
57 * @see org.exolab.castor.xml.UnmarshalListener#attributesProcessed(java.lang.Object)
59 public void attributesProcessed(Object object) {
65 * @see org.exolab.castor.xml.UnmarshalListener#fieldAdded(java.lang.String,
66 * java.lang.Object, java.lang.Object)
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);
80 * @see org.exolab.castor.xml.UnmarshalListener#initialized(java.lang.Object)
82 public void initialized(Object object) {
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.
89 * @see org.exolab.castor.xml.UnmarshalListener#unmarshalled(java.lang.Object)
91 public void unmarshalled(Object newobj) {
92 if (newobj instanceof Vobject) {
93 Vobject nobj = (Vobject) newobj;
94 nobj.set__stored_in_document(true);
96 if (nobj.isRegisterable() && nobj.___id_field!=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
109 objrefs.put(nobj_id, nobj);
111 // add to list of objects without a valid vorbaId
115 // TODO: add to list of objects without a valid vorbaId
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);
131 } catch (Exception e) {
139 * writes the VamsasDocument to the given stream.
140 * TODO: ensure that (at least) default provenance entries are written for objects.
142 * @param vorba valid VorbaIdFactory to construct any missing IDs
144 * @throws IOException
145 * @throws MarshalException
146 * @throws ValidationException
148 public static void putVamsasDocument(PrintWriter outstream, VorbaIdFactory vorba, VamsasDocument doc)
149 throws IOException, MarshalException, ValidationException {
152 throw new Error("Null VorbaIdFactory Parameter");
153 if (doc.__vorba==null)
155 doc.__ensure_instance_ids(); // this may take a while. Do we allow for cyclic references ?
156 doc.marshal(outstream);
160 * creates new VorbaId references where necessary for newly unmarshalled objects
163 * @return false if any new object references were made
165 private static boolean ensure_references(Vector unrefed, Hashtable objrefs) {
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)) {
177 if (!objrefs.get(id).equals(o))
178 throw new Error("Serious! Duplicate reference made by vorbaIdFactory!");
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 }
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!");
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.
220 while (instream.ready()) {
221 // TODO: mark objects in oobjhash prior to unmarshalling, to detect when objects have been lost through an update.
223 Object obj = unmarshaller.unmarshal(instream);
224 boolean sync=ensure_references(unrefedObj, objrefs);
225 if (!(obj instanceof Vobject))
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};
230 } catch (MarshalException e) {
231 // TODO Auto-generated catch block
233 } catch (ValidationException e) {
234 // TODO Auto-generated catch block
236 } catch (IOException e) {
237 // TODO Auto-generated catch block