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