4 package uk.ac.vamsas.client.simpleclient;
6 import java.io.IOException;
7 import java.util.Vector;
9 import org.apache.commons.logging.Log;
10 import org.apache.commons.logging.LogFactory;
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;
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
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;
37 * indicate if new data has been incorporated
39 private boolean isModified = false;
41 * Public method for internal use by SimpleClient.
42 * @return true if document has been modified.
44 public boolean isModified() {
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
55 protected ClientDocument(VamsasDocument doc, VamsasArchive docHandler, IdFactory Factory, SimpleClient sclient) {
56 super(Factory.getVorbaIdHash(), Factory);
60 * prepare Application-side dataset from the vamsas Document iohandler
62 this.sclient = sclient;
63 iohandler = docHandler;
65 _VamsasRoots=doc.getVAMSAS();
71 * @see uk.ac.vamsas.client.IClientDocument#getObject(uk.ac.vamsas.client.VorbaId)
73 public Vobject getObject(VorbaId id) {
74 if (vamsasObjects==null) {
75 log.debug("getObject called on null objrefs list.");
78 if (vamsasObjects.containsKey(id))
79 return (Vobject) vamsasObjects.get(id);
80 log.debug("Returning null Vobject reference for id "+id.getId());
87 * @see uk.ac.vamsas.client.IClientDocument#getObjects(uk.ac.vamsas.client.VorbaId[])
89 public Vobject[] getObjects(VorbaId[] ids) {
90 if (vamsasObjects==null) {
91 log.debug("getObject[] called on null vamsasObjects list.");
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]);
99 log.debug("Returning null Vobject reference for id "+ids[i].getId());
103 * internal reference to single copy of Document Roots array
105 private VAMSAS[] _VamsasRoots=null;
107 * set if the client has corrupted the Vamsas Document structure somehow.
108 * if this is set the document will never be written back to the session unless the corruption is fixed.
110 private boolean invalidModification=false;
112 protected void updateDocumentRoots() {
114 log.error("updateDocumentRoots called on null document. Probably an implementation error.");
118 if (_VamsasRoots!=null) {
119 doc.setVAMSAS(_VamsasRoots);
126 * 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)
127 * @see uk.ac.vamsas.client.IClientDocument#getVamsasRoots()
129 public VAMSAS[] getVamsasRoots() {
131 log.debug("Null document for getVamsasRoots(), returning null");
134 if (iohandler==null) {
135 // LATER: decide on read-only status of ClientDocument object
136 log.warn("getVamsasRoots() called on possibly read-only document.");
138 if (_VamsasRoots!=null)
140 VAMSAS[] roots = doc.getVAMSAS();
142 // Make a new one to return to client to get filled.
143 _VamsasRoots = new VAMSAS[] { new VAMSAS() };
144 registerObject(_VamsasRoots[0]);
145 // Do provenance now. just in case.
146 doc.getProvenance().addEntry(sclient.getProvenanceEntry("Created new document root [id="+_VamsasRoots[0].getId()+"]"));
147 doc.addVAMSAS(_VamsasRoots[0]);
149 _VamsasRoots = new VAMSAS[roots.length];
150 for (int r=0;r<roots.length; r++)
151 _VamsasRoots[r] = roots[r];
156 private int _contains(VAMSAS root, VAMSAS[] docRoots) {
159 if (docRoots==null || docRoots.length==0)
161 VorbaId d_id=null,r_id = root.getVorbaId();
162 for (int i=0,j=docRoots.length; i<j; i++)
163 if (docRoots[i]==root || (docRoots[i]!=null && (d_id=docRoots[i].getVorbaId())!=null) && d_id.equals(r_id))
169 * verify that newr version is really an intact version of the
170 * @param newVersion (may be modified)
173 * @return true if newVersion is a valid root that preserves original references
175 private boolean isValidUpdate(VAMSAS newVersion, final VAMSAS oldVersion, ClientDocument modflag) {
176 // ideal - this cascades down the two structures, ensuring that all ID'd objects in one are present in the other.
177 if (oldVersion==newVersion) {
178 // may be a virgin root element.
179 if (!newVersion.isRegistered())
181 _registerObject(newVersion); // TODO: check - this call hasn't been tested. (seems to work now)
182 modflag.isModified=true;
184 // TODO: Should attempt to repair document if client app has deleted/broken bits of it
185 if (oldVersion.is__stored_in_document()) {
186 // retrieve compare hashCodes to detect update.
187 if (oldVersion.get__last_hash()!=oldVersion.hashCode())
189 log.debug("Modified hashcode for vamsas root "+oldVersion.getVorbaId());
190 modflag.isModified = true;
192 log.debug("Unmodified vamsas root "+oldVersion.getVorbaId());
195 // just do internal validation for moment.
197 if (getSimpleClientConfig().validateUpdatedRoots())
199 newVersion.validate();
205 log.error("Validation Exception for new vamsas root :"+newVersion.getVorbaId(),e);
206 modflag.invalidModification=true;
210 // redundant ? if (oldVersion.is__stored_in_document())
211 if (!newVersion.isRegistered())
213 _registerObject(newVersion);
214 modflag.isModified=true;
217 if (getSimpleClientConfig().validateMergedRoots())
219 newVersion.validate();
221 modflag.isModified=true;
226 log.error("Validation Exception for new vamsas root :"+newVersion.getVorbaId(),e);
231 * LATER: MUCH LATER! - not needed for simple case and this routine shouldn't live in this class anymore
232 * isValidUpdate : Ideally. we efficiently walk down, comparing hashes, to deal with merging and verifying provenance for objects
234 // extract root objects
235 if (newroots != null) {
236 // check newroots for objects that were present in the old document
237 // check to see if the 'old' objects have been modified
238 // if they have ? we overwrite them with their new version, ensuring that
239 // provenance is updated.
240 // if they haven't ? do nothing ?
242 for (int i = 0, k = newroots.length; i < k; i++) {
243 if (newroots[i].isRegistered()) {
244 // easy - just check if anything has changed and do provenance
245 Vobject oldversion = getObject(newroots[i].getVorbaId());
246 if (oldversion instanceof VAMSAS) {
247 // LATER: appropriate merging behaviour when two clients have improperly modified the same Vobject independently.
248 if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
249 // client has modified this Vobject since last retrieval.
250 if (newroots[i].get__last_hash() != oldversion.get__last_hash()) {
251 // Vobject has been modified by another client since this
253 // last access to document.
258 "SimpleClient error when using setVamsasRoots : The vorbaId for Vobject "
260 + " does not refer to an Vobject of type VAMSAS in the current document!");
263 if (!newroots[i].is__stored_in_document()) {
264 // check if Vobject is modified
265 if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
266 // it is - so we add newroots[i] as a new Vobject, with updated
273 // just add newroots[i] as a new Vobject in the document
274 // - with appropriate provenance.
279 private SimpleClientConfig getSimpleClientConfig() {
280 return sclient.getSimpleClientConfig();
283 * merge old and new root vectors
284 * @param newr This array may be written to
286 * @param the client document (usually this) which this root set belongs to.
287 * @return merged vector of vamsas roots
289 private VAMSAS[] _combineRoots(VAMSAS[] newr, final VAMSAS[] original, ClientDocument modflag) {
290 Vector rts = new Vector();
291 for (int i=0,j=original.length; i<j; i++) {
292 int k = _contains(original[i], newr);
294 if (isValidUpdate(newr[k], original[i], modflag)) {
295 // set by isValidUpdate if the hashcodes were really different from last store
299 // LATER: try harder to merge ducument roots.
300 log.warn("Couldn't merge new VAMSAS root "+newr[k].getId());
301 newr[k] = null; // LATER: this means we ignore mangled roots. NOT GOOD
305 rts.add(original[i]);
308 // add remaining (new) roots
309 for (int i=0,j=newr.length; i<j; i++) {
312 modflag.isModified=true;
315 newr = new VAMSAS[rts.size()];
316 for (int i=0,j=rts.size(); i<j; i++)
317 newr[i] = (VAMSAS) rts.get(i);
322 * update the document with new roots.
323 * LATER: decide: this affects the next call to getVamsasRoots()
324 * @see org.vamsas.IClientDocument.setVamsasRoots
326 public void setVamsasRoots(VAMSAS[] newroots) {
328 log.debug("setVamsasRoots called on null document.");
332 if (newroots==null) {
333 log.debug("setVamsasRoots(null) - do nothing.");
336 // are we dealing with same array ?
337 if (_VamsasRoots!=newroots) {
338 // merge roots into local version.
339 newr = new VAMSAS[newroots.length];
340 for (int i=0;i<newr.length;i++)
341 newr[i] = newroots[i];
342 newr=_combineRoots(newr,_VamsasRoots,this);
344 newr = new VAMSAS[_VamsasRoots.length];
345 for (int i=0;i<newr.length;i++)
346 newr[i]=_VamsasRoots[i];
348 // actually compare with document root set for final combination (to ensure nothing is lost)
349 _VamsasRoots = _combineRoots(newr, doc.getVAMSAS(), this);
354 * LATER: decide: this affects the next call to getVamsasRoots()
355 * @see uk.ac.vamsas.client.IClientDocument#addVamsasRoot(uk.ac.vamsas.objects.core.VAMSAS)
357 public void addVamsasRoot(VAMSAS newroot) {
359 log.debug("addVamsasRoots called on null document.");
362 VAMSAS[] newroots = _combineRoots(new VAMSAS[] {newroot}, getVamsasRoots(), this);
363 _VamsasRoots = newroots;
369 * @see uk.ac.vamsas.client.IClientDocument#registerObjects(uk.ac.vamsas.client.Vobject[])
371 public VorbaId[] registerObjects(Vobject[] unregistered) {
373 log.warn("registerObjects[] called on null document.");
376 if (vamsasObjects==null) {
377 log.warn("registerObjects[] called for null vamsasObjects hasharray.");
380 if (unregistered!=null) {
381 VorbaId ids[] = new VorbaId[unregistered.length];
382 for (int i=0,k=unregistered.length; i<k; i++)
383 if (unregistered[i]!=null) {
384 log.warn("Null Vobject passed to registerObject[] at position "+i);
387 ids[i]=registerObject(unregistered[i]);
389 log.debug("Registered "+unregistered.length+" objects - total of "+vamsasObjects.size()+" ids.");
395 * @see uk.ac.vamsas.client.IClientDocument#registerObject(uk.ac.vamsas.client.Vobject)
397 public VorbaId registerObject(Vobject unregistered) {
399 log.warn("registerObjects called on null document.");
402 if (vamsasObjects==null) {
403 log.warn("registerObjects called for null vamsasObjects hasharray.");
406 if (iohandler==null) {
407 log.warn("registerObjects called for read only document.");
411 if (unregistered!=null) {
412 VorbaId id = _registerObject(unregistered);
413 log.debug("Registered object - total of "+vamsasObjects.size()+" ids.");
416 log.warn("Null Vobject passed to registerObject.");
420 * IClientAppdata instance - if it exists.
422 SimpleClientAppdata scappd = null;
424 * @see uk.ac.vamsas.client.IClientDocument#getClientAppdata()
426 public IClientAppdata getClientAppdata() {
427 // TODO: getClientAppdata not tested in ArchiveClient mockup
428 log.error("TODO: TEST Client Appdata access methods");
430 log.warn("getClientAppdata called on null document.");
434 log.debug("Creating new SimpleClientAppdata instance for "+sclient.getSessionHandle());
435 scappd = new SimpleClientAppdata(this);
437 // LATER: may not need this as a warning message.
438 log.warn("Null appdata object for "+sclient.getSessionHandle());
440 log.debug("Created SimpleClientAppdata successfully.");
443 log.debug("Returning existing SimpleClientAppdata reference.");
448 * access the vamsas document
449 * @return the session's vamsas document
451 protected VamsasDocument getVamsasDocument() {
455 * returns the read-only IO interface for the vamsas document Jar file
458 protected VamsasArchiveReader getVamsasArchiveReader() {
459 if (iohandler==null) {
460 log.error("Near fatal. Null VamsasArchive iohandler so can't get VamsasArchiveReader");
464 log.info("TODO: test getVamsasArchiveReader");
465 return iohandler.getOriginalArchiveReader();
466 } catch (Exception e) {
467 log.warn("Unable to create OriginalArchiveReader!", e);
472 * called by vamsas api to write updated document to session
473 * @return true if update was successful
474 * @throws java.io.IOException
476 protected boolean updateSessionDocument() throws java.io.IOException {
477 boolean docupdate = true; // 'non-serious' problems below set this false
479 log.warn("updateSessionDocument called on null document.");
480 throw new java.io.IOException("Document is closed.");
482 if (iohandler==null) {
483 log.warn("updateSessionDocument called on null document iohandler handler.");
484 throw new java.io.IOException("Document is closed.");
487 if (!isModified() && !scappd.isModified()) {
488 log.debug("Document update not necessary. returning false.");
491 VamsasSession session = sclient._session;
492 log.debug("updating Session Document in "+session.sessionDir);
493 // update the VamsasDocument structure with any new appData's.
494 // try to update the sessionFile
495 log.debug("Attempting to update session "+sclient.session.getSessionUrn());
496 if (scappd!=null && scappd.isModified()) {
497 ClientHandle client = sclient.client;
498 UserHandle user = sclient.user;
499 scappd.closeForWriting();
500 if (scappd.appsGlobal==null) {
501 log.debug("Creating new appData entry for this application...");
502 // first write for this application - add a new section in document
503 ApplicationData appd = scappd.appsGlobal = new ApplicationData();
504 appd.setName(client.getClientName());
505 // appd.setUrn(client.getClientUrn());
506 appd.setVersion(client.getVersion());
507 doc.addApplicationData(appd);
508 // embed or jarEntry ? - for now only jarEntry's are dealt with.
509 appd.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()));
510 log.debug("... created.");
512 if (scappd.newAppData!=null && scappd.newAppData.sessionFile.exists()) {
513 log.debug("Beginning update for new Global Appdata...");
514 // new global appdata to write.
515 if (scappd.appsGlobal.getData()!=null) {
516 scappd.appsGlobal.setData(null);
517 scappd.appsGlobal.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()));
519 // LATER: use a switch to decide if the data should be written as a reference or as an embedded data chunk
520 scappd.updateAnAppdataEntry(iohandler, scappd.appsGlobal, scappd.newAppData);
521 log.debug("...Successfully updated Global Appdata Entry.");
523 if (scappd.newUserData!=null && scappd.newUserData.sessionFile.exists()) {
524 log.debug("Beginning to update Users Appdata entry....");
525 if (scappd.usersData==null) {
526 // create new user appdata
527 scappd.usersData = new User();
528 scappd.usersData.setFullname(user.getFullName());
529 scappd.usersData.setOrganization(user.getOrganization());
530 scappd.appsGlobal.addUser(scappd.usersData);
532 User appd = scappd.usersData;
533 if (appd.getData()!=null || appd.getDataReference()==null) {
534 // LATER make standard appDataReference constructor for client+user
536 String safe_username = user.getFullName();
537 int t = safe_username.indexOf(" ");
539 safe_username = safe_username.substring(t);
541 appd.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()+safe_username));
543 scappd.updateAnAppdataEntry(iohandler, scappd.usersData, scappd.newUserData);
544 log.debug("...Successfully updated user AppData entry.");
548 if (iohandler.transferRemainingAppDatas())
549 log.debug("Remaining appdatas were transferred.");
551 log.debug("No remaining appdatas were transferred. (Correct?)");
552 } catch (Exception e) {
553 log.error("While transferring remaining AppDatas", e);
555 log.debug("Updating Document...");
556 // now update the document. - this was basically the doUpdate method in test.ArchiveClient
557 updateDocumentRoots();
559 iohandler.putVamsasDocument(doc);
560 log.debug("Successfully written document entry.");
562 catch (Exception e) {
563 log.error("Marshalling error for vamsas document.",e);
564 docupdate = false; // pass on the (probable) object validation error
566 iohandler.closeArchive();
567 iohandler=null; // so this method cannot be called again for this instance
568 log.debug("...successully finished and closed.");
569 return docupdate; // no errors ?
572 * @see java.lang.Object#finalize()
574 protected void finalize() throws Throwable {
575 log.debug("Garbage collecting on ClientDocument instance.");
583 // disengage from client
584 if (sclient!=null && sclient.cdocument==this)
585 sclient.cdocument = null;
590 public Vector getUpdatedObjects() {
591 // TODO: WALK through the document objects calling the update mechanism for each one, or just pass this vector back to client ?return updatedObjects;
595 * if this is set the document will never be written back to the session unless the corruption is fixed.
596 * @return the invalidModification
598 public boolean isInvalidModification() {
599 return invalidModification;
602 * set if the client has corrupted the Vamsas Document structure somehow.
603 * if this is set the document will never be written back to the session unless the corruption is fixed.
604 * @param invalidModification the invalidModification to set
606 public void setInvalidModification(boolean invalidModification) {
607 this.invalidModification = invalidModification;