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