finished the Appdata/ClientDocument update mechanism. Untested!
[vamsas.git] / src / org / vamsas / client / simpleclient / ClientDocument.java
1 /*
2  *
3  */
4 package org.vamsas.client.simpleclient;
5
6 import java.io.IOException;
7 import java.util.Vector;
8
9 import org.apache.commons.logging.Log;
10 import org.apache.commons.logging.LogFactory;
11 import org.vamsas.client.ClientHandle;
12 import org.vamsas.client.IClientAppdata;
13 import org.vamsas.client.IClientDocument;
14 import org.vamsas.client.UserHandle;
15 import org.vamsas.client.Vobject;
16 import org.vamsas.client.VorbaId;
17 import org.vamsas.objects.core.ApplicationData;
18 import org.vamsas.objects.core.User;
19 import org.vamsas.objects.core.VAMSAS;
20 import org.vamsas.objects.core.VamsasDocument;
21 import org.vamsas.objects.utils.AppDataReference;
22 import org.vamsas.test.objects.Core;
23
24 /**
25  * Maintains a collection of vamsas objects, appdatas and states, and provides api for a SimpleClient's client.
26  * @author jimp 
27  */
28 public class ClientDocument extends org.vamsas.client.ClientDocument implements IClientDocument {
29   private static Log log = LogFactory.getLog(ClientDocument.class);
30   private VamsasDocument doc;
31   protected SimpleClient sclient;
32   protected VamsasArchive archive = null;
33   /**
34    * indicate if new data has been incorporated
35    */
36   private boolean isModified = false;
37   /**
38    * Public method for internal use by SimpleClient.
39    * @return true if document has been modified.
40    */
41   public boolean isModified() {
42     return isModified;
43   }
44   private java.util.Hashtable objrefs=null;
45   /**
46    *
47    *  prepare Application-side dataset from the vamsas Document archive
48    * @param doc - the dataset
49    * @param docHandler - the sessionFile IO handler
50    * @param Factory - the source of current and new vorbaIds
51    * @param sclient - the simpleclient instance
52    */
53   protected ClientDocument(VamsasDocument doc, VamsasArchive docHandler, IdFactory Factory, SimpleClient sclient) {
54     super(Factory.getVorbaIdHash(), Factory);
55     
56     /**
57      * prepare Application-side dataset from the vamsas Document archive
58      */
59     this.sclient = sclient;
60     archive = docHandler;
61     this.doc = doc;
62     objrefs = Factory.getVorbaIdHash();
63   }
64   
65   /*
66    * (non-Javadoc)
67    * 
68    * @see org.vamsas.client.IClientDocument#getObject(org.vamsas.client.VorbaId)
69    */
70   public Vobject getObject(VorbaId id) {
71     if (objrefs.containsKey(id))
72       return (Vobject) objrefs.get(id);
73     log.debug("Returning null Vobject reference for id "+id.getId());
74     return null;
75   }
76   
77   /*
78    * (non-Javadoc)
79    * 
80    * @see org.vamsas.client.IClientDocument#getObjects(org.vamsas.client.VorbaId[])
81    */
82   public Vobject[] getObjects(VorbaId[] ids) {
83     Vobject[] vo = new Vobject[ids.length];
84     for (int i=0,j=ids.length; i<j;i++) 
85       if (objrefs.containsKey(ids[i]))
86         vo[i] = (Vobject) objrefs.get(ids[i]);
87       else
88         log.debug("Returning null Vobject reference for id "+ids[i].getId());
89     return vo;
90   }
91   /**
92    * internal reference to single copy of Document Roots array
93    */
94   private VAMSAS[] _VamsasRoots=null;
95   /*
96    * (non-Javadoc)
97    * LATER: currently there is only one Vector of roots ever passed to client - decide if this is correct (means this is not thread safe and may behave unexpectedly)
98    * @see org.vamsas.client.IClientDocument#getVamsasRoots()
99    */
100   public VAMSAS[] getVamsasRoots() {
101     if (_VamsasRoots!=null)
102       return _VamsasRoots;
103     VAMSAS[] roots = doc.getVAMSAS();
104     if (roots == null) {
105       // Make a new one to return to client : TODO: Decide if this is correct
106       _VamsasRoots = new VAMSAS[] { new VAMSAS() };
107     } else {
108       _VamsasRoots = new VAMSAS[roots.length];
109       for (int r=0;r<roots.length; r++)
110         _VamsasRoots[r] = roots[r];
111     }
112     return _VamsasRoots;
113   }
114   
115   private int _contains(VAMSAS root, VAMSAS[] docRoots) {
116     if (root==null)
117       return -1;
118     if (docRoots==null || docRoots.length==0)
119       return -1;
120     String r_id = root.getId();
121     for (int i=0,j=docRoots.length; i<j; i++)
122       if (docRoots[i]==root || (docRoots[i]!=null && docRoots[i].getId().equals(r_id)))
123         return i;
124     return -1;
125   }
126 /**
127  * verify that newr version is really an intact version of the 
128  * @param newVersion (may be modified)
129  * @param oldVersion 
130  * @return true if newVersion is a valid root that preserves original references
131  */
132   private boolean isValidUpdate(VAMSAS newVersion, final VAMSAS oldVersion) {
133     // ideal - this cascades down the two structures, ensuring that all ID'd objects in one are present in the other.
134     if (oldVersion==newVersion) {
135       // may be a virgin root element.
136       if (!newVersion.isRegistered())
137         _registerObject(newVersion);
138       // Should retrieve original version and compare - unless local hashes can be used to determine if resultSet has been truncated.
139       // just do internal validation for moment.
140       if (newVersion.isValid())
141         return true;
142       return false;
143     } else {
144       // redundant ? if (oldVersion.is__stored_in_document())
145       if (!newVersion.isRegistered())
146         _registerObject(newVersion);
147       if (newVersion.isValid())
148         return true;
149     }
150     return false;
151     /**
152      * LATER isValidUpdate : Ideally. we efficiently walk down, comparing hashes, to deal with merging and verifying provenance for objects
153     
154     // extract root objects
155     if (newroots != null) {
156       // check newroots for objects that were present in the old document
157       // check to see if the 'old' objects have been modified
158       // if they have ? we overwrite them with their new version, ensuring that
159       // provenance is updated.
160       // if they haven't ? do nothing ?
161       
162       for (int i = 0, k = newroots.length; i < k; i++) {
163         if (newroots[i].isRegistered()) {
164           // easy - just check if anything has changed and do provenance
165           Vobject oldversion = getObject(newroots[i].getVorbaId());
166           if (oldversion instanceof VAMSAS) {
167             // LATER: appropriate merging behaviour when two clients have improperly modified the same Vobject independently.
168             if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
169               // client has modified this Vobject since last retrieval.
170               if (newroots[i].get__last_hash() != oldversion.get__last_hash()) {
171                 // Vobject has been modified by another client since this
172                 // client's
173                 // last access to document.
174               }
175             }
176           } else {
177             throw new Error(
178                 "SimpleClient error when using setVamsasRoots : The vorbaId for Vobject "
179                 + i
180                 + " does not refer to an Vobject of type VAMSAS in the current document!");
181           }
182         } else {
183           if (!newroots[i].is__stored_in_document()) {
184             // check if Vobject is modified
185             if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
186               // it is - so we add newroots[i] as a new Vobject, with updated
187               // provenance.
188             } else {
189               // do nothing
190               newroots[i] = null;
191             }
192           } else {
193             // just add newroots[i] as a new Vobject in the document
194             // - with appropriate provenance.
195           }
196         }
197       }*/
198   }
199   /**
200    * merge old and new root vectors
201    * @param newr This array may be written to
202    * @param original
203    * @param the client document (usually this) which this root set belongs to.
204    * @return merged vector of vamsas roots
205    */
206   private VAMSAS[] _combineRoots(VAMSAS[] newr, final VAMSAS[] original, ClientDocument modflag) {
207     Vector rts = new Vector();
208     boolean modified=false;
209     for (int i=0,j=original.length; i<j; i++) {
210       int k = _contains(original[i], newr);
211       if (k>-1) {
212         if (isValidUpdate(newr[k], original[i])) {
213           modified=true;
214           rts.add(newr[k]);
215           newr[k]=null;
216         } else {
217           // LATER: try harder to merge ducument roots.
218           log.warn("Couldn't merge new VAMSAS root "+newr[k].getId());
219           newr[k] = null; // LATER: this means we ignore mangled roots. NOT GOOD
220         }
221       } else {
222         // add in order.
223         rts.add(original[i]);
224       }
225     }
226     // add remaining (new) roots
227     for (int i=0,j=newr.length; i<j; i++) {
228       if (newr[i]!=null) {
229         rts.add(newr[i]);
230         modified=true;
231       }
232     }
233     newr = new VAMSAS[rts.size()];
234     for (int i=0,j=rts.size(); i<j; i++)
235       newr[i] = (VAMSAS) rts.get(i);
236     if (modflag!=null)
237       modflag.isModified = modified;
238     return newr;
239   }
240   
241   /**
242    * update the document with new roots.
243    * LATER: decide: this affects the next call to getVamsasRoots()
244    * @see org.vamsas.IClientDocument.setVamsasRoots
245    */
246   public void setVamsasRoots(VAMSAS[] newroots) {
247     VAMSAS[] newr;
248     if (newroots==null) {
249       log.debug("setVamsasRoots(null) - do nothing.");
250       return;
251     }
252     // are we dealing with same array ?
253     if (_VamsasRoots!=newroots) {
254       // merge roots into local version.
255       newr = new VAMSAS[newroots.length];
256       for (int i=0;i<newr.length;i++)
257         newr[i] = newroots[i];
258       newr=_combineRoots(newr,_VamsasRoots,this);
259     } else {
260       newr = new VAMSAS[_VamsasRoots.length];
261       for (int i=0;i<newr.length;i++)
262         newr[i]=_VamsasRoots[i];
263     }
264     //  actually compare with document root set for final combination (to ensure nothing is lost)
265     _VamsasRoots = _combineRoots(newr, doc.getVAMSAS(), this); 
266   }
267   
268   
269   /* (non-Javadoc)
270    * LATER: decide: this affects the next call to getVamsasRoots()
271    * @see org.vamsas.client.IClientDocument#addVamsasRoot(org.vamsas.objects.core.VAMSAS)
272    */
273   public void addVamsasRoot(VAMSAS newroot) {
274     VAMSAS[] newroots = _combineRoots(new VAMSAS[] {newroot}, _VamsasRoots, this);
275     _VamsasRoots = newroots;  
276   }
277   
278   /*
279    * (non-Javadoc)
280    * 
281    * @see org.vamsas.client.IClientDocument#registerObjects(org.vamsas.client.Vobject[])
282    */
283   public VorbaId[] registerObjects(Vobject[] unregistered) {
284     if (unregistered!=null) {
285       VorbaId ids[] = new VorbaId[unregistered.length];
286       for (int i=0,k=unregistered.length; i<k; i++)
287         if (unregistered[i]!=null) {
288           log.warn("Null Vobject passed to registerObject[] at position "+i);
289           return null;
290         } else {
291           ids[i]=registerObject(unregistered[i]);
292         }
293       log.debug("Registered "+unregistered.length+" objects - total of "+objrefs.size()+" ids.");
294       return ids;
295     }
296     return null;
297   }
298   /* (non-Javadoc)
299    * @see org.vamsas.client.IClientDocument#registerObject(org.vamsas.client.Vobject)
300    */
301   public VorbaId registerObject(Vobject unregistered) {
302     if (unregistered!=null) {
303       VorbaId id = _registerObject(unregistered);
304       log.debug("Registered object - total of "+objrefs.size()+" ids.");
305       return id;
306     }
307     log.warn("Null Vobject passed to registerObject.");
308     return null;
309   }
310   /**
311    * IClientAppdata instance - if it exists.
312    */
313   SimpleClientAppdata scappd = null;
314   /* (non-Javadoc)
315    * @see org.vamsas.client.IClientDocument#getClientAppdata()
316    */
317   public IClientAppdata getClientAppdata() {
318     if (scappd==null) {
319       log.debug("Creating new SimpleClientAppdata instance for "+sclient.getSessionHandle());
320       scappd = new SimpleClientAppdata(this);
321       if (scappd==null) {
322         // LATER: may not need this as a warning message.
323         log.warn("Null appdata object for "+sclient.getSessionHandle());
324       } else {
325         log.debug("Created SimpleClientAppdata successfully.");
326       }
327     } else {
328       log.debug("Returning existing SimpleClientAppdata reference.");
329     }
330     return scappd;
331   }
332   /**
333    * access the vamsas document
334    * @return the session's vamsas document
335    */
336   protected VamsasDocument getVamsasDocument() {
337     return doc;
338   }
339   /**
340    * returns the read-only IO interface for the vamsas document Jar file
341    * @return
342    */
343   protected VamsasArchiveReader getVamsasArchiveReader() {
344     try {
345       return archive.getOriginalArchiveReader();
346     } catch (Exception e) {
347       log.warn("Unable to create OriginalArchiveReader!", e);
348     }
349     return null;
350   }
351   protected boolean updateSessionDocument() throws java.io.IOException {
352     boolean docupdate = true; // 'non-serious' problems below set this false
353     if (!isModified() && !scappd.isModified()) {
354       log.debug("Document update not necessary. returning false.");
355       return false;
356     }
357     VamsasSession session = sclient._session;
358     log.debug("updating Session Document in "+session.sessionDir);
359     // update the VamsasDocument structure with any new appData's.
360     // try to update the sessionFile
361     log.debug("Attempting to update session "+sclient.session.getSessionUrn());
362     if (scappd.isModified()) {
363       ClientHandle client = sclient.client;
364       UserHandle user = sclient.user;
365       scappd.closeForWriting();      
366       if (scappd.appsGlobal==null) {
367         log.debug("Creating new appData entry for this application...");
368         // first write for this application - add a new section in document
369         ApplicationData appd = scappd.appsGlobal = new ApplicationData();
370         appd.setName(client.getClientName());
371         appd.setUrn(client.getClientUrn());
372         appd.setVersion(client.getVersion());
373         doc.addApplicationData(appd);
374         // embed or jarEntry ?  - for now only jarEntry's are dealt with.
375         appd.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()));
376         log.debug("... created.");
377       }
378       if (scappd.newAppData!=null && scappd.newAppData.sessionFile.exists()) {
379         log.debug("Beginning update for new Global Appdata...");
380         // new global appdata to write.
381         if (scappd.appsGlobal.getData()!=null) {
382           scappd.appsGlobal.setData(null);
383           scappd.appsGlobal.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()));
384         }
385         // LATER: use a switch to decide if the data should be written as a reference or as an embedded data chunk
386         scappd.updateAnAppdataEntry(archive, scappd.appsGlobal, scappd.newAppData);
387         log.debug("...Successfully updated Global Appdata Entry.");
388       }
389       if (scappd.newUserData!=null && scappd.newUserData.sessionFile.exists()) {
390         log.debug("Beginning to update Users Appdata entry....");
391         if (scappd.usersData==null) {
392           // create new user appdata
393           scappd.usersData = new User();
394           scappd.usersData.setFullname(user.getFullName());
395           scappd.usersData.setOrganization(user.getOrganization());
396           scappd.appsGlobal.addUser(scappd.usersData);
397         }
398         User appd = scappd.usersData;
399         if (appd.getData()!=null || appd.getDataReference()==null) {
400           // LATER make standard appDataReference constructor for client+user 
401           appd.setData(null);          
402           String safe_username = user.getFullName();
403           int t = safe_username.indexOf(" ");
404           if (t!=-1) {
405             safe_username = safe_username.substring(t);
406           }
407           appd.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()+safe_username));
408         }
409         scappd.updateAnAppdataEntry(archive, scappd.usersData, scappd.newUserData);
410         log.debug("...Successfully updated user AppData entry.");
411       }
412     }
413     log.debug("Updating Document...");
414     // now update the document.
415     try {
416       archive.putVamsasDocument(doc);
417       log.debug("Successfully written document entry.");
418     }
419     catch (Exception e) {
420       log.error("Marshalling error for vamsas document.",e);
421       docupdate = false; // pass on the (probable) object validation error 
422     }
423     if (archive.transferRemainingAppDatas())
424       log.debug("Remaining appdatas were transferred.");
425     else
426       log.debug("No remaining appdatas were transferred. (Correct?)");
427     archive.closeArchive();
428     log.debug("...successully finished and closed.");
429
430     return docupdate; // no errors ?
431   }
432   /* (non-Javadoc)
433    * @see java.lang.Object#finalize()
434    */
435   protected void finalize() throws Throwable {
436     log.debug("Garbage collecting on ClientDocument instance.");
437     if (scappd!=null) {
438       scappd.finalize();
439       scappd = null;
440     }
441     // TODO local garbage collection
442     
443     super.finalize();
444   }
445
446 }