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