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