applied LGPLv3 and source code formatting.
[vamsas.git] / src / uk / ac / vamsas / client / simpleclient / ClientDocument.java
1 /*
2  * This file is part of the Vamsas Client version 0.1. 
3  * Copyright 2009 by Jim Procter, Iain Milne, Pierre Marguerite, 
4  *  Andrew Waterhouse and Dominik Lindner.
5  * 
6  * Earlier versions have also been incorporated into Jalview version 2.4 
7  * since 2008, and TOPALi version 2 since 2007.
8  * 
9  * The Vamsas Client is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Lesser General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *  
14  * The Vamsas Client is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Lesser General Public License for more details.
18  * 
19  * You should have received a copy of the GNU Lesser General Public License
20  * along with the Vamsas Client.  If not, see <http://www.gnu.org/licenses/>.
21  */
22 package uk.ac.vamsas.client.simpleclient;
23
24 import java.io.IOException;
25 import java.util.Vector;
26
27 import org.apache.commons.logging.Log;
28 import org.apache.commons.logging.LogFactory;
29
30 import uk.ac.vamsas.client.ClientHandle;
31 import uk.ac.vamsas.client.IClientAppdata;
32 import uk.ac.vamsas.client.IClientDocument;
33 import uk.ac.vamsas.client.UserHandle;
34 import uk.ac.vamsas.client.Vobject;
35 import uk.ac.vamsas.client.VorbaId;
36 import uk.ac.vamsas.objects.core.ApplicationData;
37 import uk.ac.vamsas.objects.core.User;
38 import uk.ac.vamsas.objects.core.VAMSAS;
39 import uk.ac.vamsas.objects.core.VamsasDocument;
40 import uk.ac.vamsas.objects.utils.AppDataReference;
41 import uk.ac.vamsas.test.objects.Core;
42
43 /**
44  * Maintains a collection of vamsas objects, appdatas and states, and provides
45  * api for a SimpleClient's client. TODO: test and migrate
46  * ArchiveClient.getAppData methods to here and retest in ExampleApplication
47  * 
48  * @author jimp
49  */
50 public class ClientDocument extends uk.ac.vamsas.client.ClientDocument
51     implements IClientDocument {
52   private static Log log = LogFactory.getLog(ClientDocument.class);
53
54   private VamsasDocument doc;
55
56   protected SimpleClient sclient;
57
58   protected VamsasArchive iohandler = null;
59
60   /**
61    * indicate if new data has been incorporated
62    */
63   private boolean isModified = false;
64
65   /**
66    * Public method for internal use by SimpleClient.
67    * 
68    * @return true if document has been modified.
69    */
70   public boolean isModified() {
71     return isModified;
72   }
73
74   /**
75    * 
76    * prepare Application-side dataset from the vamsas Document iohandler
77    * 
78    * @param doc
79    *          - the dataset
80    * @param docHandler
81    *          - the sessionFile IO handler
82    * @param Factory
83    *          - the source of current and new vorbaIds
84    * @param sclient
85    *          - the simpleclient instance
86    */
87   protected ClientDocument(VamsasDocument doc, VamsasArchive docHandler,
88       IdFactory Factory, SimpleClient sclient) {
89     super(Factory.getVorbaIdHash(), Factory);
90
91     /**
92      * prepare Application-side dataset from the vamsas Document iohandler
93      */
94     this.sclient = sclient;
95     iohandler = docHandler;
96     this.doc = doc;
97     _VamsasRoots = doc.getVAMSAS();
98   }
99
100   /*
101    * (non-Javadoc)
102    * 
103    * @see
104    * uk.ac.vamsas.client.IClientDocument#getObject(uk.ac.vamsas.client.VorbaId)
105    */
106   public Vobject getObject(VorbaId id) {
107     if (vamsasObjects == null) {
108       log.debug("getObject called on null objrefs list.");
109       return null;
110     }
111     if (vamsasObjects.containsKey(id))
112       return (Vobject) vamsasObjects.get(id);
113     log.debug("Returning null Vobject reference for id " + id.getId());
114     return null;
115   }
116
117   /*
118    * (non-Javadoc)
119    * 
120    * @see
121    * uk.ac.vamsas.client.IClientDocument#getObjects(uk.ac.vamsas.client.VorbaId
122    * [])
123    */
124   public Vobject[] getObjects(VorbaId[] ids) {
125     if (vamsasObjects == null) {
126       log.debug("getObject[]  called on null vamsasObjects list.");
127       return null;
128     }
129     Vobject[] vo = new Vobject[ids.length];
130     for (int i = 0, j = ids.length; i < j; i++)
131       if (vamsasObjects.containsKey(ids[i]))
132         vo[i] = (Vobject) vamsasObjects.get(ids[i]);
133       else
134         log.debug("Returning null Vobject reference for id " + ids[i].getId());
135     return vo;
136   }
137
138   /**
139    * internal reference to single copy of Document Roots array
140    */
141   private VAMSAS[] _VamsasRoots = null;
142
143   /**
144    * set if the client has corrupted the Vamsas Document structure somehow. if
145    * this is set the document will never be written back to the session unless
146    * the corruption is fixed.
147    */
148   private boolean invalidModification = false;
149
150   protected void updateDocumentRoots() {
151     if (doc == null) {
152       log
153           .error("updateDocumentRoots called on null document. Probably an implementation error.");
154       return;
155     }
156     if (isModified) {
157       if (_VamsasRoots != null) {
158         doc.setVAMSAS(_VamsasRoots);
159         _VamsasRoots = null;
160       }
161     }
162   }
163
164   /*
165    * (non-Javadoc) LATER: currently there is only one Vector of roots ever
166    * passed to client - decide if this is correct (means this is not thread safe
167    * and may behave unexpectedly)
168    * 
169    * @see uk.ac.vamsas.client.IClientDocument#getVamsasRoots()
170    */
171   public VAMSAS[] getVamsasRoots() {
172     if (doc == null) {
173       log.debug("Null document for getVamsasRoots(), returning null");
174       return null;
175     }
176     if (iohandler == null) {
177       // LATER: decide on read-only status of ClientDocument object
178       log.warn("getVamsasRoots() called on possibly read-only document.");
179     }
180     if (_VamsasRoots != null)
181       return _VamsasRoots;
182     VAMSAS[] roots = doc.getVAMSAS();
183     if (roots == null) {
184       // Make a new one to return to client to get filled.
185       _VamsasRoots = new VAMSAS[] { new VAMSAS() };
186       registerObject(_VamsasRoots[0]);
187       // Do provenance now. just in case.
188       doc.getProvenance().addEntry(
189           sclient.getProvenanceEntry("Created new document root [id="
190               + _VamsasRoots[0].getId() + "]"));
191       doc.addVAMSAS(_VamsasRoots[0]);
192     } else {
193       _VamsasRoots = new VAMSAS[roots.length];
194       for (int r = 0; r < roots.length; r++)
195         _VamsasRoots[r] = roots[r];
196     }
197     return _VamsasRoots;
198   }
199
200   private int _contains(VAMSAS root, VAMSAS[] docRoots) {
201     if (root == null)
202       return -1;
203     if (docRoots == null || docRoots.length == 0)
204       return -1;
205     VorbaId d_id = null, r_id = root.getVorbaId();
206     for (int i = 0, j = docRoots.length; i < j; i++)
207       if (docRoots[i] == root
208           || (docRoots[i] != null && (d_id = docRoots[i].getVorbaId()) != null)
209           && d_id.equals(r_id))
210         return i;
211     return -1;
212   }
213
214   /**
215    * verify that newr version is really an intact version of the
216    * 
217    * @param newVersion
218    *          (may be modified)
219    * @param oldVersion
220    * @param modflag
221    * @return true if newVersion is a valid root that preserves original
222    *         references
223    */
224   private boolean isValidUpdate(VAMSAS newVersion, final VAMSAS oldVersion,
225       ClientDocument modflag) {
226     // ideal - this cascades down the two structures, ensuring that all ID'd
227     // objects in one are present in the other.
228     if (oldVersion == newVersion) {
229       // may be a virgin root element.
230       if (!newVersion.isRegistered()) {
231         _registerObject(newVersion); // TODO: check - this call hasn't been
232                                      // tested. (seems to work now)
233         modflag.isModified = true;
234       }
235       // TODO: Should attempt to repair document if client app has
236       // deleted/broken bits of it
237       if (oldVersion.is__stored_in_document()) {
238         // retrieve compare hashCodes to detect update.
239         if (oldVersion.get__last_hash() != oldVersion.hashCode()) {
240           log.debug("Modified hashcode for vamsas root "
241               + oldVersion.getVorbaId());
242           modflag.isModified = true;
243         } else {
244           log.debug("Unmodified vamsas root " + oldVersion.getVorbaId());
245         }
246       }
247       // just do internal validation for moment.
248       try {
249         if (getSimpleClientConfig().validateUpdatedRoots()) {
250           newVersion.validate();
251         }
252         return true;
253       } catch (Exception e) {
254         log.error("Validation Exception for new vamsas root :"
255             + newVersion.getVorbaId(), e);
256         modflag.invalidModification = true;
257       }
258       return false;
259     } else {
260       // redundant ? if (oldVersion.is__stored_in_document())
261       if (!newVersion.isRegistered()) {
262         _registerObject(newVersion);
263         modflag.isModified = true;
264       }
265       try {
266         if (getSimpleClientConfig().validateMergedRoots()) {
267           newVersion.validate();
268         }
269         modflag.isModified = true;
270         return true;
271       } catch (Exception e) {
272         log.error("Validation Exception for new vamsas root :"
273             + newVersion.getVorbaId(), e);
274       }
275     }
276     return false;
277     /**
278      * LATER: MUCH LATER! - not needed for simple case and this routine
279      * shouldn't live in this class anymore isValidUpdate : Ideally. we
280      * efficiently walk down, comparing hashes, to deal with merging and
281      * verifying provenance for objects
282      * 
283      * // extract root objects if (newroots != null) { // check newroots for
284      * objects that were present in the old document // check to see if the
285      * 'old' objects have been modified // if they have ? we overwrite them with
286      * their new version, ensuring that // provenance is updated. // if they
287      * haven't ? do nothing ?
288      * 
289      * for (int i = 0, k = newroots.length; i < k; i++) { if
290      * (newroots[i].isRegistered()) { // easy - just check if anything has
291      * changed and do provenance Vobject oldversion =
292      * getObject(newroots[i].getVorbaId()); if (oldversion instanceof VAMSAS) {
293      * // LATER: appropriate merging behaviour when two clients have improperly
294      * modified the same Vobject independently. if (newroots[i].get__last_hash()
295      * != newroots[i].hashCode()) { // client has modified this Vobject since
296      * last retrieval. if (newroots[i].get__last_hash() !=
297      * oldversion.get__last_hash()) { // Vobject has been modified by another
298      * client since this // client's // last access to document. } } } else {
299      * throw new Error(
300      * "SimpleClient error when using setVamsasRoots : The vorbaId for Vobject "
301      * + i +
302      * " does not refer to an Vobject of type VAMSAS in the current document!");
303      * } } else { if (!newroots[i].is__stored_in_document()) { // check if
304      * Vobject is modified if (newroots[i].get__last_hash() !=
305      * newroots[i].hashCode()) { // it is - so we add newroots[i] as a new
306      * Vobject, with updated // provenance. } else { // do nothing newroots[i] =
307      * null; } } else { // just add newroots[i] as a new Vobject in the document
308      * // - with appropriate provenance. } } }
309      */
310   }
311
312   private SimpleClientConfig getSimpleClientConfig() {
313     return sclient.getSimpleClientConfig();
314   }
315
316   /**
317    * merge old and new root vectors
318    * 
319    * @param newr
320    *          This array may be written to
321    * @param original
322    * @param the
323    *          client document (usually this) which this root set belongs to.
324    * @return merged vector of vamsas roots
325    */
326   private VAMSAS[] _combineRoots(VAMSAS[] newr, final VAMSAS[] original,
327       ClientDocument modflag) {
328     Vector rts = new Vector();
329     for (int i = 0, j = original.length; i < j; i++) {
330       int k = _contains(original[i], newr);
331       if (k > -1) {
332         if (isValidUpdate(newr[k], original[i], modflag)) {
333           // set by isValidUpdate if the hashcodes were really different from
334           // last store
335           rts.add(newr[k]);
336           newr[k] = null;
337         } else {
338           // LATER: try harder to merge ducument roots.
339           log.warn("Couldn't merge new VAMSAS root " + newr[k].getId());
340           newr[k] = null; // LATER: this means we ignore mangled roots. NOT GOOD
341         }
342       } else {
343         // add in order.
344         rts.add(original[i]);
345       }
346     }
347     // add remaining (new) roots
348     for (int i = 0, j = newr.length; i < j; i++) {
349       if (newr[i] != null) {
350         rts.add(newr[i]);
351         modflag.isModified = true;
352       }
353     }
354     newr = new VAMSAS[rts.size()];
355     for (int i = 0, j = rts.size(); i < j; i++)
356       newr[i] = (VAMSAS) rts.get(i);
357     return newr;
358   }
359
360   /**
361    * update the document with new roots. LATER: decide: this affects the next
362    * call to getVamsasRoots()
363    * 
364    * @see org.vamsas.IClientDocument.setVamsasRoots
365    */
366   public void setVamsasRoots(VAMSAS[] newroots) {
367     if (doc == null) {
368       log.debug("setVamsasRoots called on null document.");
369       return;
370     }
371     VAMSAS[] newr;
372     if (newroots == null) {
373       log.debug("setVamsasRoots(null) - do nothing.");
374       return;
375     }
376     // are we dealing with same array ?
377     if (_VamsasRoots != newroots) {
378       // merge roots into local version.
379       newr = new VAMSAS[newroots.length];
380       for (int i = 0; i < newr.length; i++)
381         newr[i] = newroots[i];
382       newr = _combineRoots(newr, _VamsasRoots, this);
383     } else {
384       newr = new VAMSAS[_VamsasRoots.length];
385       for (int i = 0; i < newr.length; i++)
386         newr[i] = _VamsasRoots[i];
387     }
388     // actually compare with document root set for final combination (to ensure
389     // nothing is lost)
390     _VamsasRoots = _combineRoots(newr, doc.getVAMSAS(), this);
391   }
392
393   /*
394    * (non-Javadoc) LATER: decide: this affects the next call to getVamsasRoots()
395    * 
396    * @see
397    * uk.ac.vamsas.client.IClientDocument#addVamsasRoot(uk.ac.vamsas.objects.
398    * core.VAMSAS)
399    */
400   public void addVamsasRoot(VAMSAS newroot) {
401     if (doc == null) {
402       log.debug("addVamsasRoots called on null document.");
403       return;
404     }
405     VAMSAS[] newroots = _combineRoots(new VAMSAS[] { newroot },
406         getVamsasRoots(), this);
407     _VamsasRoots = newroots;
408   }
409
410   /*
411    * (non-Javadoc)
412    * 
413    * @see
414    * uk.ac.vamsas.client.IClientDocument#registerObjects(uk.ac.vamsas.client
415    * .Vobject[])
416    */
417   public VorbaId[] registerObjects(Vobject[] unregistered) {
418     if (doc == null) {
419       log.warn("registerObjects[] called on null document.");
420       return null;
421     }
422     if (vamsasObjects == null) {
423       log.warn("registerObjects[] called for null vamsasObjects hasharray.");
424       return null;
425     }
426     if (unregistered != null) {
427       VorbaId ids[] = new VorbaId[unregistered.length];
428       for (int i = 0, k = unregistered.length; i < k; i++)
429         if (unregistered[i] != null) {
430           log.warn("Null Vobject passed to registerObject[] at position " + i);
431           return null;
432         } else {
433           ids[i] = registerObject(unregistered[i]);
434         }
435       log.debug("Registered " + unregistered.length + " objects - total of "
436           + vamsasObjects.size() + " ids.");
437       return ids;
438     }
439     return null;
440   }
441
442   /*
443    * (non-Javadoc)
444    * 
445    * @see
446    * uk.ac.vamsas.client.IClientDocument#registerObject(uk.ac.vamsas.client.
447    * Vobject)
448    */
449   public VorbaId registerObject(Vobject unregistered) {
450     if (doc == null) {
451       log.warn("registerObjects called on null document.");
452       return null;
453     }
454     if (vamsasObjects == null) {
455       log.warn("registerObjects called for null vamsasObjects hasharray.");
456       return null;
457     }
458     if (iohandler == null) {
459       log.warn("registerObjects called for read only document.");
460       return null;
461     }
462
463     if (unregistered != null) {
464       VorbaId id = _registerObject(unregistered);
465       log.debug("Registered object - total of " + vamsasObjects.size()
466           + " ids.");
467       return id;
468     }
469     log.warn("Null Vobject passed to registerObject.");
470     return null;
471   }
472
473   /**
474    * IClientAppdata instance - if it exists.
475    */
476   SimpleClientAppdata scappd = null;
477
478   /*
479    * (non-Javadoc)
480    * 
481    * @see uk.ac.vamsas.client.IClientDocument#getClientAppdata()
482    */
483   public IClientAppdata getClientAppdata() {
484     // TODO: getClientAppdata not tested in ArchiveClient mockup
485     log.error("TODO: TEST Client Appdata access methods");
486     if (doc == null) {
487       log.warn("getClientAppdata called on null document.");
488       return null;
489     }
490     if (scappd == null) {
491       log.debug("Creating new SimpleClientAppdata instance for "
492           + sclient.getSessionHandle());
493       scappd = new SimpleClientAppdata(this);
494       if (scappd == null) {
495         // LATER: may not need this as a warning message.
496         log.warn("Null appdata object for " + sclient.getSessionHandle());
497       } else {
498         log.debug("Created SimpleClientAppdata successfully.");
499       }
500     } else {
501       log.debug("Returning existing SimpleClientAppdata reference.");
502     }
503     return scappd;
504   }
505
506   /**
507    * access the vamsas document
508    * 
509    * @return the session's vamsas document
510    */
511   protected VamsasDocument getVamsasDocument() {
512     return doc;
513   }
514
515   /**
516    * returns the read-only IO interface for the vamsas document Jar file
517    * 
518    * @return
519    */
520   protected VamsasArchiveReader getVamsasArchiveReader() {
521     if (iohandler == null) {
522       log
523           .error("Near fatal. Null VamsasArchive iohandler so can't get VamsasArchiveReader");
524       return null;
525     }
526     try {
527       log.info("TODO: test getVamsasArchiveReader");
528       return iohandler.getOriginalArchiveReader();
529     } catch (Exception e) {
530       log.warn("Unable to create OriginalArchiveReader!", e);
531     }
532     return null;
533   }
534
535   /**
536    * called by vamsas api to write updated document to session
537    * 
538    * @return true if update was successful
539    * @throws java.io.IOException
540    */
541   protected boolean updateSessionDocument() throws java.io.IOException {
542     boolean docupdate = true; // 'non-serious' problems below set this false
543     if (doc == null) {
544       log.warn("updateSessionDocument called on null document.");
545       throw new java.io.IOException("Document is closed.");
546     }
547     if (iohandler == null) {
548       log
549           .warn("updateSessionDocument called on null document iohandler handler.");
550       throw new java.io.IOException("Document is closed.");
551     }
552
553     if (!isModified() && !scappd.isModified()) {
554       log.debug("Document update not necessary. returning false.");
555       return false;
556     }
557     VamsasSession session = sclient._session;
558     log.debug("updating Session Document in " + session.sessionDir);
559     // update the VamsasDocument structure with any new appData's.
560     // try to update the sessionFile
561     log
562         .debug("Attempting to update session "
563             + sclient.session.getSessionUrn());
564     if (scappd != null && scappd.isModified()) {
565       ClientHandle client = sclient.client;
566       UserHandle user = sclient.user;
567       scappd.closeForWriting();
568       if (scappd.appsGlobal == null) {
569         log.debug("Creating new appData entry for this application...");
570         // first write for this application - add a new section in document
571         ApplicationData appd = scappd.appsGlobal = new ApplicationData();
572         appd.setName(client.getClientName());
573         // appd.setUrn(client.getClientUrn());
574         appd.setVersion(client.getVersion());
575         doc.addApplicationData(appd);
576         // embed or jarEntry ? - for now only jarEntry's are dealt with.
577         appd.setDataReference(AppDataReference.uniqueAppDataReference(doc,
578             sclient.client.getClientUrn()));
579         log.debug("... created.");
580       }
581       if (scappd.newAppData != null && scappd.newAppData.sessionFile.exists()) {
582         log.debug("Beginning update for new Global Appdata...");
583         // new global appdata to write.
584         if (scappd.appsGlobal.getData() != null) {
585           scappd.appsGlobal.setData(null);
586           scappd.appsGlobal.setDataReference(AppDataReference
587               .uniqueAppDataReference(doc, sclient.client.getClientUrn()));
588         }
589         // LATER: use a switch to decide if the data should be written as a
590         // reference or as an embedded data chunk
591         scappd.updateAnAppdataEntry(iohandler, scappd.appsGlobal,
592             scappd.newAppData);
593         log.debug("...Successfully updated Global Appdata Entry.");
594       }
595       if (scappd.newUserData != null && scappd.newUserData.sessionFile.exists()) {
596         log.debug("Beginning to update Users Appdata entry....");
597         if (scappd.usersData == null) {
598           // create new user appdata
599           scappd.usersData = new User();
600           scappd.usersData.setFullname(user.getFullName());
601           scappd.usersData.setOrganization(user.getOrganization());
602           scappd.appsGlobal.addUser(scappd.usersData);
603         }
604         User appd = scappd.usersData;
605         if (appd.getData() != null || appd.getDataReference() == null) {
606           // LATER make standard appDataReference constructor for client+user
607           appd.setData(null);
608           String safe_username = user.getFullName();
609           int t = safe_username.indexOf(" ");
610           if (t != -1) {
611             safe_username = safe_username.substring(t);
612           }
613           appd.setDataReference(AppDataReference.uniqueAppDataReference(doc,
614               sclient.client.getClientUrn() + safe_username));
615         }
616         scappd.updateAnAppdataEntry(iohandler, scappd.usersData,
617             scappd.newUserData);
618         log.debug("...Successfully updated user AppData entry.");
619       }
620     }
621     try {
622       if (iohandler.transferRemainingAppDatas())
623         log.debug("Remaining appdatas were transferred.");
624       else
625         log.debug("No remaining appdatas were transferred. (Correct?)");
626     } catch (Exception e) {
627       log.error("While transferring remaining AppDatas", e);
628     }
629     log.debug("Updating Document...");
630     // now update the document. - this was basically the doUpdate method in
631     // test.ArchiveClient
632     updateDocumentRoots();
633     try {
634       iohandler.putVamsasDocument(doc);
635       log.debug("Successfully written document entry.");
636     } catch (Exception e) {
637       log.error("Marshalling error for vamsas document.", e);
638       docupdate = false; // pass on the (probable) object validation error
639     }
640     iohandler.closeArchive();
641     iohandler = null; // so this method cannot be called again for this instance
642     log.debug("...successully finished and closed.");
643     return docupdate; // no errors ?
644   }
645
646   /*
647    * (non-Javadoc)
648    * 
649    * @see java.lang.Object#finalize()
650    */
651   protected void finalize() throws Throwable {
652     log.debug("Garbage collecting on ClientDocument instance.");
653     if (scappd != null) {
654       scappd.finalize();
655       scappd = null;
656     }
657     if (doc != null) {
658       doc = null;
659     }
660     // disengage from client
661     if (sclient != null && sclient.cdocument == this)
662       sclient.cdocument = null;
663     sclient = null;
664
665     super.finalize();
666   }
667
668   public Vector getUpdatedObjects() {
669     // TODO: WALK through the document objects calling the update mechanism for
670     // each one, or just pass this vector back to client ?return updatedObjects;
671     return null;
672   }
673
674   /**
675    * if this is set the document will never be written back to the session
676    * unless the corruption is fixed.
677    * 
678    * @return the invalidModification
679    */
680   public boolean isInvalidModification() {
681     return invalidModification;
682   }
683
684   /**
685    * set if the client has corrupted the Vamsas Document structure somehow. if
686    * this is set the document will never be written back to the session unless
687    * the corruption is fixed.
688    * 
689    * @param invalidModification
690    *          the invalidModification to set
691    */
692   public void setInvalidModification(boolean invalidModification) {
693     this.invalidModification = invalidModification;
694   }
695 }