ef0a7d50318965acceaaf52e2769c6a3b9c64b4f
[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  * @return true if newVersion is a valid root that preserves original references
168  */
169   private boolean isValidUpdate(VAMSAS newVersion, final VAMSAS oldVersion) {
170     // ideal - this cascades down the two structures, ensuring that all ID'd objects in one are present in the other.
171     if (oldVersion==newVersion) {
172       // may be a virgin root element.
173       if (!newVersion.isRegistered())
174         _registerObject(newVersion); // TODO: check - this call hasn't been tested.
175       // Should retrieve original version and compare - unless local hashes can be used to determine if resultSet has been truncated.
176       // just do internal validation for moment.
177       try {
178         if (SimpleClientConfig.validateUpdatedRoots())
179           newVersion.validate();
180         return true;
181       }
182       catch (Exception e)
183       {
184         log.error("Validation Exception for new vamsas root :"+newVersion.getVorbaId(),e);
185       }
186       return false;
187     } else {
188       // redundant ? if (oldVersion.is__stored_in_document())
189       if (!newVersion.isRegistered())
190         _registerObject(newVersion);
191       try {
192         if (SimpleClientConfig.validateMergedRoots())
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     }
201     return false;
202     /**
203      * LATER: MUCH LATER! - not needed for simple case and this routine shouldn't live in this class anymore 
204      * isValidUpdate : Ideally. we efficiently walk down, comparing hashes, to deal with merging and verifying provenance for objects
205     
206     // extract root objects
207     if (newroots != null) {
208       // check newroots for objects that were present in the old document
209       // check to see if the 'old' objects have been modified
210       // if they have ? we overwrite them with their new version, ensuring that
211       // provenance is updated.
212       // if they haven't ? do nothing ?
213       
214       for (int i = 0, k = newroots.length; i < k; i++) {
215         if (newroots[i].isRegistered()) {
216           // easy - just check if anything has changed and do provenance
217           Vobject oldversion = getObject(newroots[i].getVorbaId());
218           if (oldversion instanceof VAMSAS) {
219             // LATER: appropriate merging behaviour when two clients have improperly modified the same Vobject independently.
220             if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
221               // client has modified this Vobject since last retrieval.
222               if (newroots[i].get__last_hash() != oldversion.get__last_hash()) {
223                 // Vobject has been modified by another client since this
224                 // client's
225                 // last access to document.
226               }
227             }
228           } else {
229             throw new Error(
230                 "SimpleClient error when using setVamsasRoots : The vorbaId for Vobject "
231                 + i
232                 + " does not refer to an Vobject of type VAMSAS in the current document!");
233           }
234         } else {
235           if (!newroots[i].is__stored_in_document()) {
236             // check if Vobject is modified
237             if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
238               // it is - so we add newroots[i] as a new Vobject, with updated
239               // provenance.
240             } else {
241               // do nothing
242               newroots[i] = null;
243             }
244           } else {
245             // just add newroots[i] as a new Vobject in the document
246             // - with appropriate provenance.
247           }
248         }
249       }*/
250   }
251   /**
252    * merge old and new root vectors
253    * @param newr This array may be written to
254    * @param original
255    * @param the client document (usually this) which this root set belongs to.
256    * @return merged vector of vamsas roots
257    */
258   private VAMSAS[] _combineRoots(VAMSAS[] newr, final VAMSAS[] original, ClientDocument modflag) {
259     Vector rts = new Vector();
260     boolean modified=false;
261     for (int i=0,j=original.length; i<j; i++) {
262       int k = _contains(original[i], newr);
263       if (k>-1) {
264         if (isValidUpdate(newr[k], original[i])) {
265           modified=true;
266           rts.add(newr[k]);
267           newr[k]=null;
268         } else {
269           // LATER: try harder to merge ducument roots.
270           log.warn("Couldn't merge new VAMSAS root "+newr[k].getId());
271           newr[k] = null; // LATER: this means we ignore mangled roots. NOT GOOD
272         }
273       } else {
274         // add in order.
275         rts.add(original[i]);
276       }
277     }
278     // add remaining (new) roots
279     for (int i=0,j=newr.length; i<j; i++) {
280       if (newr[i]!=null) {
281         rts.add(newr[i]);
282         modified=true;
283       }
284     }
285     newr = new VAMSAS[rts.size()];
286     for (int i=0,j=rts.size(); i<j; i++)
287       newr[i] = (VAMSAS) rts.get(i);
288     if (modflag!=null)
289       modflag.isModified = modified;
290     return newr;
291   }
292   
293   /**
294    * update the document with new roots.
295    * LATER: decide: this affects the next call to getVamsasRoots()
296    * @see org.vamsas.IClientDocument.setVamsasRoots
297    */
298   public void setVamsasRoots(VAMSAS[] newroots) {
299     if (doc==null) {
300       log.debug("setVamsasRoots called on null document.");
301       return;
302     }
303     VAMSAS[] newr;
304     if (newroots==null) {
305       log.debug("setVamsasRoots(null) - do nothing.");
306       return;
307     }
308     // are we dealing with same array ?
309     if (_VamsasRoots!=newroots) {
310       // merge roots into local version.
311       newr = new VAMSAS[newroots.length];
312       for (int i=0;i<newr.length;i++)
313         newr[i] = newroots[i];
314       newr=_combineRoots(newr,_VamsasRoots,this);
315     } else {
316       newr = new VAMSAS[_VamsasRoots.length];
317       for (int i=0;i<newr.length;i++)
318         newr[i]=_VamsasRoots[i];
319     }
320     //  actually compare with document root set for final combination (to ensure nothing is lost)
321     _VamsasRoots = _combineRoots(newr, doc.getVAMSAS(), this); 
322   }
323   
324   
325   /* (non-Javadoc)
326    * LATER: decide: this affects the next call to getVamsasRoots()
327    * @see uk.ac.vamsas.client.IClientDocument#addVamsasRoot(uk.ac.vamsas.objects.core.VAMSAS)
328    */
329   public void addVamsasRoot(VAMSAS newroot) {
330     if (doc==null) {
331       log.debug("addVamsasRoots called on null document.");
332       return;
333     }
334     VAMSAS[] newroots = _combineRoots(new VAMSAS[] {newroot}, getVamsasRoots(), this);
335     _VamsasRoots = newroots;  
336   }
337   
338   /*
339    * (non-Javadoc)
340    * 
341    * @see uk.ac.vamsas.client.IClientDocument#registerObjects(uk.ac.vamsas.client.Vobject[])
342    */
343   public VorbaId[] registerObjects(Vobject[] unregistered) {
344     if (doc==null) {
345       log.warn("registerObjects[] called on null document.");
346       return null;
347     }
348     if (vamsasObjects==null) {
349       log.warn("registerObjects[] called for null vamsasObjects hasharray.");
350       return null;
351     }
352     if (unregistered!=null) {
353       VorbaId ids[] = new VorbaId[unregistered.length];
354       for (int i=0,k=unregistered.length; i<k; i++)
355         if (unregistered[i]!=null) {
356           log.warn("Null Vobject passed to registerObject[] at position "+i);
357           return null;
358         } else {
359           ids[i]=registerObject(unregistered[i]);
360         }
361       log.debug("Registered "+unregistered.length+" objects - total of "+vamsasObjects.size()+" ids.");
362       return ids;
363     }
364     return null;
365   }
366   /* (non-Javadoc)
367    * @see uk.ac.vamsas.client.IClientDocument#registerObject(uk.ac.vamsas.client.Vobject)
368    */
369   public VorbaId registerObject(Vobject unregistered) {
370     if (doc==null) {
371       log.warn("registerObjects called on null document.");
372       return null;
373     }
374     if (vamsasObjects==null) {
375       log.warn("registerObjects called for null vamsasObjects hasharray.");
376       return null;
377     }
378     if (iohandler==null)  {
379       log.warn("registerObjects called for read only document.");
380       return null;
381     }
382       
383     if (unregistered!=null) {
384       VorbaId id = _registerObject(unregistered);
385       log.debug("Registered object - total of "+vamsasObjects.size()+" ids.");
386       return id;
387     }
388     log.warn("Null Vobject passed to registerObject.");
389     return null;
390   }
391   /**
392    * IClientAppdata instance - if it exists.
393    */
394   SimpleClientAppdata scappd = null;
395   /* (non-Javadoc)
396    * @see uk.ac.vamsas.client.IClientDocument#getClientAppdata()
397    */
398   public IClientAppdata getClientAppdata() {
399     // TODO: getClientAppdata not tested in ArchiveClient mockup
400     log.error("TODO: TEST Client Appdata access methods");
401     if (doc==null) {
402       log.warn("getClientAppdata called on null document.");
403       return null;
404     }
405     if (scappd==null) {
406       log.debug("Creating new SimpleClientAppdata instance for "+sclient.getSessionHandle());
407       scappd = new SimpleClientAppdata(this);
408       if (scappd==null) {
409         // LATER: may not need this as a warning message.
410         log.warn("Null appdata object for "+sclient.getSessionHandle());
411       } else {
412         log.debug("Created SimpleClientAppdata successfully.");
413       }
414     } else {
415       log.debug("Returning existing SimpleClientAppdata reference.");
416     }
417     return scappd;
418   }
419   /**
420    * access the vamsas document
421    * @return the session's vamsas document
422    */
423   protected VamsasDocument getVamsasDocument() {
424     return doc;
425   }
426   /**
427    * returns the read-only IO interface for the vamsas document Jar file
428    * @return
429    */
430   protected VamsasArchiveReader getVamsasArchiveReader() {
431     if (iohandler==null) {
432       log.error("Near fatal. Null VamsasArchive iohandler so can't get VamsasArchiveReader");
433       return null;
434     }
435     try {
436       log.info("TODO: test getVamsasArchiveReader");
437       return iohandler.getOriginalArchiveReader();
438     } catch (Exception e) {
439       log.warn("Unable to create OriginalArchiveReader!", e);
440     }
441     return null;
442   }
443   /**
444    * called by vamsas api to write updated document to session
445    * @return true if update was successful
446    * @throws java.io.IOException
447    */
448   protected boolean updateSessionDocument() throws java.io.IOException {
449     boolean docupdate = true; // 'non-serious' problems below set this false
450     if (doc==null) {
451       log.warn("updateSessionDocument called on null document.");
452       throw new java.io.IOException("Document is closed.");
453     }
454     if (iohandler==null) {
455       log.warn("updateSessionDocument called document iohandler handler.");
456       throw new java.io.IOException("Document is closed.");
457     }
458     
459     if (!isModified() && !scappd.isModified()) {
460       log.debug("Document update not necessary. returning false.");
461       return false;
462     }
463     VamsasSession session = sclient._session;
464     log.debug("updating Session Document in "+session.sessionDir);
465     // update the VamsasDocument structure with any new appData's.
466     // try to update the sessionFile
467     log.debug("Attempting to update session "+sclient.session.getSessionUrn());
468     if (scappd!=null && scappd.isModified()) {
469       ClientHandle client = sclient.client;
470       UserHandle user = sclient.user;
471       scappd.closeForWriting();      
472       if (scappd.appsGlobal==null) {
473         log.debug("Creating new appData entry for this application...");
474         // first write for this application - add a new section in document
475         ApplicationData appd = scappd.appsGlobal = new ApplicationData();
476         appd.setName(client.getClientName());
477         // appd.setUrn(client.getClientUrn());
478         appd.setVersion(client.getVersion());
479         doc.addApplicationData(appd);
480         // embed or jarEntry ?  - for now only jarEntry's are dealt with.
481         appd.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()));
482         log.debug("... created.");
483       }
484       if (scappd.newAppData!=null && scappd.newAppData.sessionFile.exists()) {
485         log.debug("Beginning update for new Global Appdata...");
486         // new global appdata to write.
487         if (scappd.appsGlobal.getData()!=null) {
488           scappd.appsGlobal.setData(null);
489           scappd.appsGlobal.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()));
490         }
491         // LATER: use a switch to decide if the data should be written as a reference or as an embedded data chunk
492         scappd.updateAnAppdataEntry(iohandler, scappd.appsGlobal, scappd.newAppData);
493         log.debug("...Successfully updated Global Appdata Entry.");
494       }
495       if (scappd.newUserData!=null && scappd.newUserData.sessionFile.exists()) {
496         log.debug("Beginning to update Users Appdata entry....");
497         if (scappd.usersData==null) {
498           // create new user appdata
499           scappd.usersData = new User();
500           scappd.usersData.setFullname(user.getFullName());
501           scappd.usersData.setOrganization(user.getOrganization());
502           scappd.appsGlobal.addUser(scappd.usersData);
503         }
504         User appd = scappd.usersData;
505         if (appd.getData()!=null || appd.getDataReference()==null) {
506           // LATER make standard appDataReference constructor for client+user 
507           appd.setData(null);          
508           String safe_username = user.getFullName();
509           int t = safe_username.indexOf(" ");
510           if (t!=-1) {
511             safe_username = safe_username.substring(t);
512           }
513           appd.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()+safe_username));
514         }
515         scappd.updateAnAppdataEntry(iohandler, scappd.usersData, scappd.newUserData);
516         log.debug("...Successfully updated user AppData entry.");
517       }
518     }
519     try {
520       if (iohandler.transferRemainingAppDatas())
521         log.debug("Remaining appdatas were transferred.");
522       else
523         log.debug("No remaining appdatas were transferred. (Correct?)");
524     } catch (Exception e) {
525       log.error("While transferring remaining AppDatas", e);
526     }
527     log.debug("Updating Document...");
528     // now update the document. - this was basically the doUpdate method in test.ArchiveClient
529     updateDocumentRoots();
530     try {
531       iohandler.putVamsasDocument(doc);
532       log.debug("Successfully written document entry.");
533     }
534     catch (Exception e) {
535       log.error("Marshalling error for vamsas document.",e);
536       docupdate = false; // pass on the (probable) object validation error 
537     }
538     iohandler.closeArchive();
539     iohandler=null; // so this method cannot be called again for this instance
540     log.debug("...successully finished and closed.");
541     return docupdate; // no errors ?
542   }
543   /* (non-Javadoc)
544    * @see java.lang.Object#finalize()
545    */
546   protected void finalize() throws Throwable {
547     log.debug("Garbage collecting on ClientDocument instance.");
548     if (scappd!=null) {
549       scappd.finalize();
550       scappd = null;
551     }
552     if (doc!=null) {
553       doc = null;
554     }
555     // disengage from client
556     if (sclient!=null)
557       sclient.cdocument = null;
558     sclient=null;
559     
560     super.finalize();
561   }
562   public Vector getUpdatedObjects() {
563     // TODO: WALK through the document objects calling the update mechanism for each one, or just pass this vector back to client ?return updatedObjects;
564     return null;
565   }
566 }