fixed the User element and the form of the ApplicationData dataType.xsd definition.
[vamsas.git] / src / org / vamsas / client / VorbaXmlBinder.java
1 /**
2  * 
3  */
4 package org.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.exolab.castor.mapping.FieldHandler;
16 import org.exolab.castor.mapping.GeneralizedFieldHandler;
17 import org.exolab.castor.mapping.ValidityException;
18 import org.exolab.castor.xml.IDResolver;
19 import org.exolab.castor.xml.MarshalException;
20 import org.exolab.castor.xml.MarshalListener;
21 import org.exolab.castor.xml.Marshaller;
22 import org.exolab.castor.xml.UnmarshalListener;
23 import org.exolab.castor.xml.Unmarshaller;
24 import org.exolab.castor.xml.ValidationException;
25 import org.vamsas.objects.core.VamsasDocument;
26 /**
27  * Implements the Vamsas object ID machinery for translating 
28  * between non-volatile XML IDs and object references. Use the
29  * marshalling and unmarshalling methods in this class in order
30  * to avoid validation exceptions when marshalling new objects
31  * into the vamsas document.
32  */
33 public class VorbaXmlBinder implements UnmarshalListener {
34   private final IVorbaIdFactory vorbafactory;
35
36   private final Vector obj;
37
38   private final Hashtable objrefs;
39
40   public VorbaXmlBinder(IVorbaIdFactory vorbafactory, Vector obj, Hashtable objrefs) {
41     this.vorbafactory = vorbafactory;
42     this.obj = obj;
43     this.objrefs = objrefs;
44   }
45
46   /*
47    * (non-Javadoc)
48    * 
49    * @see org.exolab.castor.xml.UnmarshalListener#attributesProcessed(java.lang.Object)
50    */
51   public void attributesProcessed(Object object) {
52   }
53
54   /*
55    * (non-Javadoc)
56    * 
57    * @see org.exolab.castor.xml.UnmarshalListener#fieldAdded(java.lang.String,
58    *      java.lang.Object, java.lang.Object)
59    */
60   public void fieldAdded(String fieldName, Object parent, Object child) {
61   }
62
63   /*
64    * (non-Javadoc)
65    * 
66    * @see org.exolab.castor.xml.UnmarshalListener#initialized(java.lang.Object)
67    */
68   public void initialized(Object object) {
69   }
70   
71   /*
72    * Check if the object has an 'id' field - if it does, copy the value into
73    * the VorbaId field of object, and add the object to the VorbaId hash.
74    * 
75    * @see org.exolab.castor.xml.UnmarshalListener#unmarshalled(java.lang.Object)
76    */
77   public void unmarshalled(Object newobj) {
78     if (newobj instanceof object) {
79       object nobj = (object) newobj;
80       nobj.set__stored_in_document(true);
81       Field fd = null;
82       try {
83         if (nobj.isRegisterable()) {
84           // look for the id field (should be an NCName string)
85           nobj.__vorba = vorbafactory;
86           fd = nobj.getClass().getField("id");
87           String idstring;
88           if (fd.get(nobj) != null) {
89             idstring = (String) fd.get(nobj);
90             if (idstring.length() > 0) {
91               if (!objrefs.containsKey(idstring)) {
92                 objrefs.put(idstring, nobj);
93                 nobj.setVorbaId(VorbaId.newId(idstring));
94               } else {
95                 System.err.println("Serious problem : duplicate id '"+idstring+"' found! expect badness.");
96                 // TODO: HANDLE duplicate XML ids correctly
97               }
98             } else {
99               // add to list of objects without a valid vorbaId
100               obj.add(nobj);
101             }
102           } else {
103             // add to list of objects without a valid vorbaId
104             obj.add(nobj);
105           }
106           
107         nobj.doHash();
108       }
109       } catch (Exception e) {
110         return;
111       };
112       
113     }
114   }
115
116   /**
117    * writes the VamsasDocument to the given stream.
118    * TODO: ensure that (at least) default provenance entries are written for objects.
119    * @param outstream
120    * @param vorba valid VorbaIdFactory to construct any missing IDs 
121    * @param doc
122    * @throws IOException
123    * @throws MarshalException
124    * @throws ValidationException
125    */
126   public static void putVamsasDocument(PrintWriter outstream, VorbaIdFactory vorba, VamsasDocument doc)
127       throws IOException, MarshalException, ValidationException {
128     // Ensure references
129     if (vorba==null)
130       throw new Error("Null VorbaIdVactory Parameter");
131     if (doc.__vorba==null)
132       doc.__vorba = vorba;
133     doc.__ensure_instance_ids(); // this may take a while. Do we allow for cyclic references ? 
134     doc.marshal(outstream);
135   }
136
137   private static boolean ensure_references(Vector unrefed, Hashtable objrefs) {
138     boolean sync=true;
139     if (unrefed.size()>0) {
140       sync=false; // document is out of sync - ids have been created.
141       java.util.Iterator newobj = unrefed.listIterator();
142       while (newobj.hasNext()) {
143         object o = (object) newobj.next();
144         // forces registration and id field update.
145         VorbaId id = o.getVorbaId();
146         if (!objrefs.containsKey(id)) {
147           objrefs.put(id.id, o);
148         } else {
149           throw new Error("Serious! Duplicate reference made by vorbaIdFactory!");
150         }
151       }
152     }
153     return sync;
154   }
155   /**
156      * Unmarshals a vamsasDocument object from a stream, registers
157      * unregistered objects, records existing VorbaIds, and completes 
158      * the org.vamsas.client.object housekeeping fields.
159      * For a valid unmarshalling, the array of returned objects also includes
160      * a <return>sync</return> parameter which is true if new VorbaIds
161      * were created. If sync is false, then the caller should ensure that the
162      * vamsasDocument is written back to disk to propagate the new VorbaIds.
163      *  TODO: ensure that provenance is correct for newly registered objects
164      * @param instream - the XML input stream 
165    * @param factory - the SimpleClient's properly configured VorbaId factory to make new references.
166    * @param root the root element's org.vamsas.objects.core object.
167      * @return null or {(Object) VamsasDocument object, (Object) Hashtable of object references, (Object) Boolean(sync) }
168      */
169   public static Object[] getVamsasObjects(Reader instream,
170         IVorbaIdFactory factory, object root) {
171       Unmarshaller unmarshaller = new Unmarshaller(root);
172       unmarshaller.setIDResolver(new IDResolver() {
173         public Object resolve(String id) {
174           System.err.println("Warning - id " + id
175               + " is not found in the VamsasDocument!");
176           return null;
177         }
178       });
179       Hashtable refbase = new Hashtable();
180       Vector unrefed = new Vector();
181       final Hashtable objrefs = refbase;
182       final IVorbaIdFactory vorbafactory = factory;
183       final Vector unrefedObj =  unrefed;
184       unmarshaller.setUnmarshalListener(new VorbaXmlBinder(vorbafactory, unrefedObj, objrefs));
185       // Call the unmarshaller.
186       try {
187         while (instream.ready()) {
188           Object obj = unmarshaller.unmarshal(instream);
189           boolean sync=ensure_references(unrefed, objrefs);
190           if (!(obj instanceof object))
191             return null;
192           return new Object[] { obj, objrefs, new Boolean(sync)};
193           }
194       } catch (MarshalException e) {
195         // TODO Auto-generated catch block
196         e.printStackTrace();
197       } catch (ValidationException e) {
198         // TODO Auto-generated catch block
199         e.printStackTrace();
200       } catch (IOException e) {
201         // TODO Auto-generated catch block
202         e.printStackTrace();
203       }
204       return null;
205     }
206 }