ensure that document updates only occur if the vamsas objects have been changed or...
[vamsas.git] / src / uk / ac / vamsas / client / simpleclient / ClientDocument.java
1 /*
2  *
3  */
4 package uk.ac.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
12 import uk.ac.vamsas.client.ClientHandle;
13 import uk.ac.vamsas.client.IClientAppdata;
14 import uk.ac.vamsas.client.IClientDocument;
15 import uk.ac.vamsas.client.UserHandle;
16 import uk.ac.vamsas.client.Vobject;
17 import uk.ac.vamsas.client.VorbaId;
18 import uk.ac.vamsas.objects.core.ApplicationData;
19 import uk.ac.vamsas.objects.core.User;
20 import uk.ac.vamsas.objects.core.VAMSAS;
21 import uk.ac.vamsas.objects.core.VamsasDocument;
22 import uk.ac.vamsas.objects.utils.AppDataReference;
23 import uk.ac.vamsas.test.objects.Core;
24
25 /**
26  * Maintains a collection of vamsas objects, appdatas and states, 
27  * and provides api for a SimpleClient's client.
28  * TODO: test and migrate ArchiveClient.getAppData methods to here and retest in ExampleApplication
29  * @author jimp 
30  */
31 public class ClientDocument extends uk.ac.vamsas.client.ClientDocument implements IClientDocument {
32   private static Log log = LogFactory.getLog(ClientDocument.class);
33   private VamsasDocument doc;
34   protected SimpleClient sclient;
35   protected VamsasArchive iohandler = null;
36   /**
37    * indicate if new data has been incorporated
38    */
39   private boolean isModified = false;
40   /**
41    * Public method for internal use by SimpleClient.
42    * @return true if document has been modified.
43    */
44   public boolean isModified() {
45     return isModified;
46   }
47   /**
48    *
49    *  prepare Application-side dataset from the vamsas Document iohandler
50    * @param doc - the dataset
51    * @param docHandler - the sessionFile IO handler
52    * @param Factory - the source of current and new vorbaIds
53    * @param sclient - the simpleclient instance
54    */
55   protected ClientDocument(VamsasDocument doc, VamsasArchive docHandler, IdFactory Factory, SimpleClient sclient) {
56     super(Factory.getVorbaIdHash(), Factory);
57     
58     
59     /**
60      * prepare Application-side dataset from the vamsas Document iohandler
61      */
62     this.sclient = sclient;
63     iohandler = docHandler;
64     this.doc = doc;
65     _VamsasRoots=doc.getVAMSAS();
66   }
67   
68   /*
69    * (non-Javadoc)
70    * 
71    * @see uk.ac.vamsas.client.IClientDocument#getObject(uk.ac.vamsas.client.VorbaId)
72    */
73   public Vobject getObject(VorbaId id) {
74     if (vamsasObjects==null) {
75       log.debug("getObject called on null objrefs list.");
76       return null;
77     }
78     if (vamsasObjects.containsKey(id))
79       return (Vobject) vamsasObjects.get(id);
80     log.debug("Returning null Vobject reference for id "+id.getId());
81     return null;
82   }
83   
84   /*
85    * (non-Javadoc)
86    * 
87    * @see uk.ac.vamsas.client.IClientDocument#getObjects(uk.ac.vamsas.client.VorbaId[])
88    */
89   public Vobject[] getObjects(VorbaId[] ids) {
90     if (vamsasObjects==null) {
91       log.debug("getObject[]  called on null vamsasObjects list.");
92       return null;
93     }
94     Vobject[] vo = new Vobject[ids.length];
95     for (int i=0,j=ids.length; i<j;i++) 
96       if (vamsasObjects.containsKey(ids[i]))
97         vo[i] = (Vobject) vamsasObjects.get(ids[i]);
98       else
99         log.debug("Returning null Vobject reference for id "+ids[i].getId());
100     return vo;
101   }
102   /**
103    * internal reference to single copy of Document Roots array
104    */
105   private VAMSAS[] _VamsasRoots=null;
106
107   protected void updateDocumentRoots() {
108     if (doc==null) {
109       log.error("updateDocumentRoots called on null document. Probably an implementation error.");
110       return;
111     }
112     if (isModified) {
113       if (_VamsasRoots!=null) {
114         doc.setVAMSAS(_VamsasRoots);
115         _VamsasRoots=null;
116       }
117     }
118   }
119 /*
120    * (non-Javadoc)
121    * 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)
122    * @see uk.ac.vamsas.client.IClientDocument#getVamsasRoots()
123    */
124   public VAMSAS[] getVamsasRoots() {
125     if (doc==null) {
126       log.debug("Null document for getVamsasRoots(), returning null");
127       return null;
128     }
129     if (iohandler==null) {
130       // LATER: decide on read-only status of ClientDocument object
131       log.warn("getVamsasRoots() called on possibly read-only document.");
132     }
133     if (_VamsasRoots!=null)
134       return _VamsasRoots;
135     VAMSAS[] roots = doc.getVAMSAS();
136     if (roots == null) {
137       // Make a new one to return to client to get filled. 
138       _VamsasRoots = new VAMSAS[] { new VAMSAS() };
139       registerObject(_VamsasRoots[0]);
140       // Do provenance now. just in case.
141       doc.getProvenance().addEntry(sclient.getProvenanceEntry("Created new document root [id="+_VamsasRoots[0].getId()+"]"));
142       doc.addVAMSAS(_VamsasRoots[0]);
143     } else {
144       _VamsasRoots = new VAMSAS[roots.length];
145       for (int r=0;r<roots.length; r++)
146         _VamsasRoots[r] = roots[r];
147     }
148     return _VamsasRoots;
149   }
150   
151   private int _contains(VAMSAS root, VAMSAS[] docRoots) {
152     if (root==null)
153       return -1;
154     if (docRoots==null || docRoots.length==0)
155       return -1;
156     VorbaId d_id=null,r_id = root.getVorbaId();
157     for (int i=0,j=docRoots.length; i<j; i++)
158       if (docRoots[i]==root || (docRoots[i]!=null && (d_id=docRoots[i].getVorbaId())!=null) && d_id.equals(r_id))
159         return i;
160     return -1;
161   }
162   
163 /**
164  * verify that newr version is really an intact version of the 
165  * @param newVersion (may be modified)
166  * @param oldVersion 
167  * @param modflag 
168  * @return true if newVersion is a valid root that preserves original references
169  */
170   private boolean isValidUpdate(VAMSAS newVersion, final VAMSAS oldVersion, ClientDocument modflag) {
171     // ideal - this cascades down the two structures, ensuring that all ID'd objects in one are present in the other.
172     if (oldVersion==newVersion) {
173       // may be a virgin root element.
174       if (!newVersion.isRegistered())
175       {
176         _registerObject(newVersion); // TODO: check - this call hasn't been tested. (seems to work now)
177         modflag.isModified=true;
178       }
179       // TODO: Should attempt to repair document if client app has deleted/broken bits of it
180       if (oldVersion.is__stored_in_document()) {
181         // retrieve compare hashCodes to detect update.
182         if (oldVersion.get__last_hash()!=oldVersion.hashCode())
183         {
184           log.debug("Modified hashcode for vamsas root "+oldVersion.getVorbaId());
185           modflag.isModified = true;
186         } else {
187           log.debug("Unmodified vamsas root "+oldVersion.getVorbaId());
188         }
189       }
190       // just do internal validation for moment.
191       try {
192         if (SimpleClientConfig.validateUpdatedRoots())
193           newVersion.validate();
194         return true;
195       }
196       catch (Exception e)
197       {
198         log.error("Validation Exception for new vamsas root :"+newVersion.getVorbaId(),e);
199       }
200       return false;
201     } else {
202       // redundant ? if (oldVersion.is__stored_in_document())
203       if (!newVersion.isRegistered())
204       {
205         _registerObject(newVersion);
206         modflag.isModified=true;
207       }
208       try {
209         if (SimpleClientConfig.validateMergedRoots())
210         {
211           newVersion.validate();
212         }
213         modflag.isModified=true;
214         return true;
215       }
216       catch (Exception e)
217       {
218         log.error("Validation Exception for new vamsas root :"+newVersion.getVorbaId(),e);
219       }
220     }
221     return false;
222     /**
223      * LATER: MUCH LATER! - not needed for simple case and this routine shouldn't live in this class anymore 
224      * isValidUpdate : Ideally. we efficiently walk down, comparing hashes, to deal with merging and verifying provenance for objects
225     
226     // extract root objects
227     if (newroots != null) {
228       // check newroots for objects that were present in the old document
229       // check to see if the 'old' objects have been modified
230       // if they have ? we overwrite them with their new version, ensuring that
231       // provenance is updated.
232       // if they haven't ? do nothing ?
233       
234       for (int i = 0, k = newroots.length; i < k; i++) {
235         if (newroots[i].isRegistered()) {
236           // easy - just check if anything has changed and do provenance
237           Vobject oldversion = getObject(newroots[i].getVorbaId());
238           if (oldversion instanceof VAMSAS) {
239             // LATER: appropriate merging behaviour when two clients have improperly modified the same Vobject independently.
240             if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
241               // client has modified this Vobject since last retrieval.
242               if (newroots[i].get__last_hash() != oldversion.get__last_hash()) {
243                 // Vobject has been modified by another client since this
244                 // client's
245                 // last access to document.
246               }
247             }
248           } else {
249             throw new Error(
250                 "SimpleClient error when using setVamsasRoots : The vorbaId for Vobject "
251                 + i
252                 + " does not refer to an Vobject of type VAMSAS in the current document!");
253           }
254         } else {
255           if (!newroots[i].is__stored_in_document()) {
256             // check if Vobject is modified
257             if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
258               // it is - so we add newroots[i] as a new Vobject, with updated
259               // provenance.
260             } else {
261               // do nothing
262               newroots[i] = null;
263             }
264           } else {
265             // just add newroots[i] as a new Vobject in the document
266             // - with appropriate provenance.
267           }
268         }
269       }*/
270   }
271   /**
272    * merge old and new root vectors
273    * @param newr This array may be written to
274    * @param original
275    * @param the client document (usually this) which this root set belongs to.
276    * @return merged vector of vamsas roots
277    */
278   private VAMSAS[] _combineRoots(VAMSAS[] newr, final VAMSAS[] original, ClientDocument modflag) {
279     Vector rts = new Vector();
280     boolean modified=false;
281     for (int i=0,j=original.length; i<j; i++) {
282       int k = _contains(original[i], newr);
283       if (k>-1) {
284         if (isValidUpdate(newr[k], original[i], modflag)) {
285           // set by isValidUpdate if the hashcodes were really different from last store 
286           rts.add(newr[k]);
287           newr[k]=null;
288         } else {
289           // LATER: try harder to merge ducument roots.
290           log.warn("Couldn't merge new VAMSAS root "+newr[k].getId());
291           newr[k] = null; // LATER: this means we ignore mangled roots. NOT GOOD
292         }
293       } else {
294         // add in order.
295         rts.add(original[i]);
296       }
297     }
298     // add remaining (new) roots
299     for (int i=0,j=newr.length; i<j; i++) {
300       if (newr[i]!=null) {
301         rts.add(newr[i]);
302         modflag.isModified=true;
303       }
304     }
305     newr = new VAMSAS[rts.size()];
306     for (int i=0,j=rts.size(); i<j; i++)
307       newr[i] = (VAMSAS) rts.get(i);
308     return newr;
309   }
310   
311   /**
312    * update the document with new roots.
313    * LATER: decide: this affects the next call to getVamsasRoots()
314    * @see org.vamsas.IClientDocument.setVamsasRoots
315    */
316   public void setVamsasRoots(VAMSAS[] newroots) {
317     if (doc==null) {
318       log.debug("setVamsasRoots called on null document.");
319       return;
320     }
321     VAMSAS[] newr;
322     if (newroots==null) {
323       log.debug("setVamsasRoots(null) - do nothing.");
324       return;
325     }
326     // are we dealing with same array ?
327     if (_VamsasRoots!=newroots) {
328       // merge roots into local version.
329       newr = new VAMSAS[newroots.length];
330       for (int i=0;i<newr.length;i++)
331         newr[i] = newroots[i];
332       newr=_combineRoots(newr,_VamsasRoots,this);
333     } else {
334       newr = new VAMSAS[_VamsasRoots.length];
335       for (int i=0;i<newr.length;i++)
336         newr[i]=_VamsasRoots[i];
337     }
338     //  actually compare with document root set for final combination (to ensure nothing is lost)
339     _VamsasRoots = _combineRoots(newr, doc.getVAMSAS(), this); 
340   }
341   
342   
343   /* (non-Javadoc)
344    * LATER: decide: this affects the next call to getVamsasRoots()
345    * @see uk.ac.vamsas.client.IClientDocument#addVamsasRoot(uk.ac.vamsas.objects.core.VAMSAS)
346    */
347   public void addVamsasRoot(VAMSAS newroot) {
348     if (doc==null) {
349       log.debug("addVamsasRoots called on null document.");
350       return;
351     }
352     VAMSAS[] newroots = _combineRoots(new VAMSAS[] {newroot}, getVamsasRoots(), this);
353     _VamsasRoots = newroots;  
354   }
355   
356   /*
357    * (non-Javadoc)
358    * 
359    * @see uk.ac.vamsas.client.IClientDocument#registerObjects(uk.ac.vamsas.client.Vobject[])
360    */
361   public VorbaId[] registerObjects(Vobject[] unregistered) {
362     if (doc==null) {
363       log.warn("registerObjects[] called on null document.");
364       return null;
365     }
366     if (vamsasObjects==null) {
367       log.warn("registerObjects[] called for null vamsasObjects hasharray.");
368       return null;
369     }
370     if (unregistered!=null) {
371       VorbaId ids[] = new VorbaId[unregistered.length];
372       for (int i=0,k=unregistered.length; i<k; i++)
373         if (unregistered[i]!=null) {
374           log.warn("Null Vobject passed to registerObject[] at position "+i);
375           return null;
376         } else {
377           ids[i]=registerObject(unregistered[i]);
378         }
379       log.debug("Registered "+unregistered.length+" objects - total of "+vamsasObjects.size()+" ids.");
380       return ids;
381     }
382     return null;
383   }
384   /* (non-Javadoc)
385    * @see uk.ac.vamsas.client.IClientDocument#registerObject(uk.ac.vamsas.client.Vobject)
386    */
387   public VorbaId registerObject(Vobject unregistered) {
388     if (doc==null) {
389       log.warn("registerObjects called on null document.");
390       return null;
391     }
392     if (vamsasObjects==null) {
393       log.warn("registerObjects called for null vamsasObjects hasharray.");
394       return null;
395     }
396     if (iohandler==null)  {
397       log.warn("registerObjects called for read only document.");
398       return null;
399     }
400       
401     if (unregistered!=null) {
402       VorbaId id = _registerObject(unregistered);
403       log.debug("Registered object - total of "+vamsasObjects.size()+" ids.");
404       return id;
405     }
406     log.warn("Null Vobject passed to registerObject.");
407     return null;
408   }
409   /**
410    * IClientAppdata instance - if it exists.
411    */
412   SimpleClientAppdata scappd = null;
413   /* (non-Javadoc)
414    * @see uk.ac.vamsas.client.IClientDocument#getClientAppdata()
415    */
416   public IClientAppdata getClientAppdata() {
417     // TODO: getClientAppdata not tested in ArchiveClient mockup
418     log.error("TODO: TEST Client Appdata access methods");
419     if (doc==null) {
420       log.warn("getClientAppdata called on null document.");
421       return null;
422     }
423     if (scappd==null) {
424       log.debug("Creating new SimpleClientAppdata instance for "+sclient.getSessionHandle());
425       scappd = new SimpleClientAppdata(this);
426       if (scappd==null) {
427         // LATER: may not need this as a warning message.
428         log.warn("Null appdata object for "+sclient.getSessionHandle());
429       } else {
430         log.debug("Created SimpleClientAppdata successfully.");
431       }
432     } else {
433       log.debug("Returning existing SimpleClientAppdata reference.");
434     }
435     return scappd;
436   }
437   /**
438    * access the vamsas document
439    * @return the session's vamsas document
440    */
441   protected VamsasDocument getVamsasDocument() {
442     return doc;
443   }
444   /**
445    * returns the read-only IO interface for the vamsas document Jar file
446    * @return
447    */
448   protected VamsasArchiveReader getVamsasArchiveReader() {
449     if (iohandler==null) {
450       log.error("Near fatal. Null VamsasArchive iohandler so can't get VamsasArchiveReader");
451       return null;
452     }
453     try {
454       log.info("TODO: test getVamsasArchiveReader");
455       return iohandler.getOriginalArchiveReader();
456     } catch (Exception e) {
457       log.warn("Unable to create OriginalArchiveReader!", e);
458     }
459     return null;
460   }
461   /**
462    * called by vamsas api to write updated document to session
463    * @return true if update was successful
464    * @throws java.io.IOException
465    */
466   protected boolean updateSessionDocument() throws java.io.IOException {
467     boolean docupdate = true; // 'non-serious' problems below set this false
468     if (doc==null) {
469       log.warn("updateSessionDocument called on null document.");
470       throw new java.io.IOException("Document is closed.");
471     }
472     if (iohandler==null) {
473       log.warn("updateSessionDocument called document iohandler handler.");
474       throw new java.io.IOException("Document is closed.");
475     }
476     
477     if (!isModified() && !scappd.isModified()) {
478       log.debug("Document update not necessary. returning false.");
479       return false;
480     }
481     VamsasSession session = sclient._session;
482     log.debug("updating Session Document in "+session.sessionDir);
483     // update the VamsasDocument structure with any new appData's.
484     // try to update the sessionFile
485     log.debug("Attempting to update session "+sclient.session.getSessionUrn());
486     if (scappd!=null && scappd.isModified()) {
487       ClientHandle client = sclient.client;
488       UserHandle user = sclient.user;
489       scappd.closeForWriting();      
490       if (scappd.appsGlobal==null) {
491         log.debug("Creating new appData entry for this application...");
492         // first write for this application - add a new section in document
493         ApplicationData appd = scappd.appsGlobal = new ApplicationData();
494         appd.setName(client.getClientName());
495         // appd.setUrn(client.getClientUrn());
496         appd.setVersion(client.getVersion());
497         doc.addApplicationData(appd);
498         // embed or jarEntry ?  - for now only jarEntry's are dealt with.
499         appd.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()));
500         log.debug("... created.");
501       }
502       if (scappd.newAppData!=null && scappd.newAppData.sessionFile.exists()) {
503         log.debug("Beginning update for new Global Appdata...");
504         // new global appdata to write.
505         if (scappd.appsGlobal.getData()!=null) {
506           scappd.appsGlobal.setData(null);
507           scappd.appsGlobal.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()));
508         }
509         // LATER: use a switch to decide if the data should be written as a reference or as an embedded data chunk
510         scappd.updateAnAppdataEntry(iohandler, scappd.appsGlobal, scappd.newAppData);
511         log.debug("...Successfully updated Global Appdata Entry.");
512       }
513       if (scappd.newUserData!=null && scappd.newUserData.sessionFile.exists()) {
514         log.debug("Beginning to update Users Appdata entry....");
515         if (scappd.usersData==null) {
516           // create new user appdata
517           scappd.usersData = new User();
518           scappd.usersData.setFullname(user.getFullName());
519           scappd.usersData.setOrganization(user.getOrganization());
520           scappd.appsGlobal.addUser(scappd.usersData);
521         }
522         User appd = scappd.usersData;
523         if (appd.getData()!=null || appd.getDataReference()==null) {
524           // LATER make standard appDataReference constructor for client+user 
525           appd.setData(null);          
526           String safe_username = user.getFullName();
527           int t = safe_username.indexOf(" ");
528           if (t!=-1) {
529             safe_username = safe_username.substring(t);
530           }
531           appd.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()+safe_username));
532         }
533         scappd.updateAnAppdataEntry(iohandler, scappd.usersData, scappd.newUserData);
534         log.debug("...Successfully updated user AppData entry.");
535       }
536     }
537     try {
538       if (iohandler.transferRemainingAppDatas())
539         log.debug("Remaining appdatas were transferred.");
540       else
541         log.debug("No remaining appdatas were transferred. (Correct?)");
542     } catch (Exception e) {
543       log.error("While transferring remaining AppDatas", e);
544     }
545     log.debug("Updating Document...");
546     // now update the document. - this was basically the doUpdate method in test.ArchiveClient
547     updateDocumentRoots();
548     try {
549       iohandler.putVamsasDocument(doc);
550       log.debug("Successfully written document entry.");
551     }
552     catch (Exception e) {
553       log.error("Marshalling error for vamsas document.",e);
554       docupdate = false; // pass on the (probable) object validation error 
555     }
556     iohandler.closeArchive();
557     iohandler=null; // so this method cannot be called again for this instance
558     log.debug("...successully finished and closed.");
559     return docupdate; // no errors ?
560   }
561   /* (non-Javadoc)
562    * @see java.lang.Object#finalize()
563    */
564   protected void finalize() throws Throwable {
565     log.debug("Garbage collecting on ClientDocument instance.");
566     if (scappd!=null) {
567       scappd.finalize();
568       scappd = null;
569     }
570     if (doc!=null) {
571       doc = null;
572     }
573     // disengage from client
574     if (sclient!=null)
575       sclient.cdocument = null;
576     sclient=null;
577     
578     super.finalize();
579   }
580   public Vector getUpdatedObjects() {
581     // TODO: WALK through the document objects calling the update mechanism for each one, or just pass this vector back to client ?return updatedObjects;
582     return null;
583   }
584 }