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