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 protected void updateDocumentRoots() {
109 log.error("updateDocumentRoots called on null document. Probably an implementation error.");
113 if (_VamsasRoots!=null) {
114 doc.setVAMSAS(_VamsasRoots);
121 * 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)
122 * @see uk.ac.vamsas.client.IClientDocument#getVamsasRoots()
124 public VAMSAS[] getVamsasRoots() {
126 log.debug("Null document for getVamsasRoots(), returning null");
129 if (iohandler==null) {
130 // LATER: decide on read-only status of ClientDocument object
131 log.warn("getVamsasRoots() called on possibly read-only document.");
133 if (_VamsasRoots!=null)
135 VAMSAS[] roots = doc.getVAMSAS();
137 // Make a new one to return to client to get filled.
138 _VamsasRoots = new VAMSAS[] { new VAMSAS() };
139 registerObject(_VamsasRoots[0]);
140 // Do provenance now. just in case.
141 doc.getProvenance().addEntry(sclient.getProvenanceEntry("Created new document root [id="+_VamsasRoots[0].getId()+"]"));
142 doc.addVAMSAS(_VamsasRoots[0]);
144 _VamsasRoots = new VAMSAS[roots.length];
145 for (int r=0;r<roots.length; r++)
146 _VamsasRoots[r] = roots[r];
151 private int _contains(VAMSAS root, VAMSAS[] docRoots) {
154 if (docRoots==null || docRoots.length==0)
156 VorbaId d_id=null,r_id = root.getVorbaId();
157 for (int i=0,j=docRoots.length; i<j; i++)
158 if (docRoots[i]==root || (docRoots[i]!=null && (d_id=docRoots[i].getVorbaId())!=null) && d_id.equals(r_id))
164 * verify that newr version is really an intact version of the
165 * @param newVersion (may be modified)
167 * @return true if newVersion is a valid root that preserves original references
169 private boolean isValidUpdate(VAMSAS newVersion, final VAMSAS oldVersion) {
170 // ideal - this cascades down the two structures, ensuring that all ID'd objects in one are present in the other.
171 if (oldVersion==newVersion) {
172 // may be a virgin root element.
173 if (!newVersion.isRegistered())
174 _registerObject(newVersion); // TODO: check - this call hasn't been tested.
175 // Should retrieve original version and compare - unless local hashes can be used to determine if resultSet has been truncated.
176 // just do internal validation for moment.
178 newVersion.validate();
183 log.error("Validation Exception for new vamsas root :"+newVersion.getVorbaId(),e);
187 // redundant ? if (oldVersion.is__stored_in_document())
188 if (!newVersion.isRegistered())
189 _registerObject(newVersion);
191 newVersion.validate();
196 log.error("Validation Exception for new vamsas root :"+newVersion.getVorbaId(),e);
201 * LATER: MUCH LATER! - not needed for simple case and this routine shouldn't live in this class anymore
202 * isValidUpdate : Ideally. we efficiently walk down, comparing hashes, to deal with merging and verifying provenance for objects
204 // extract root objects
205 if (newroots != null) {
206 // check newroots for objects that were present in the old document
207 // check to see if the 'old' objects have been modified
208 // if they have ? we overwrite them with their new version, ensuring that
209 // provenance is updated.
210 // if they haven't ? do nothing ?
212 for (int i = 0, k = newroots.length; i < k; i++) {
213 if (newroots[i].isRegistered()) {
214 // easy - just check if anything has changed and do provenance
215 Vobject oldversion = getObject(newroots[i].getVorbaId());
216 if (oldversion instanceof VAMSAS) {
217 // LATER: appropriate merging behaviour when two clients have improperly modified the same Vobject independently.
218 if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
219 // client has modified this Vobject since last retrieval.
220 if (newroots[i].get__last_hash() != oldversion.get__last_hash()) {
221 // Vobject has been modified by another client since this
223 // last access to document.
228 "SimpleClient error when using setVamsasRoots : The vorbaId for Vobject "
230 + " does not refer to an Vobject of type VAMSAS in the current document!");
233 if (!newroots[i].is__stored_in_document()) {
234 // check if Vobject is modified
235 if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
236 // it is - so we add newroots[i] as a new Vobject, with updated
243 // just add newroots[i] as a new Vobject in the document
244 // - with appropriate provenance.
250 * merge old and new root vectors
251 * @param newr This array may be written to
253 * @param the client document (usually this) which this root set belongs to.
254 * @return merged vector of vamsas roots
256 private VAMSAS[] _combineRoots(VAMSAS[] newr, final VAMSAS[] original, ClientDocument modflag) {
257 Vector rts = new Vector();
258 boolean modified=false;
259 for (int i=0,j=original.length; i<j; i++) {
260 int k = _contains(original[i], newr);
262 if (isValidUpdate(newr[k], original[i])) {
267 // LATER: try harder to merge ducument roots.
268 log.warn("Couldn't merge new VAMSAS root "+newr[k].getId());
269 newr[k] = null; // LATER: this means we ignore mangled roots. NOT GOOD
273 rts.add(original[i]);
276 // add remaining (new) roots
277 for (int i=0,j=newr.length; i<j; i++) {
283 newr = new VAMSAS[rts.size()];
284 for (int i=0,j=rts.size(); i<j; i++)
285 newr[i] = (VAMSAS) rts.get(i);
287 modflag.isModified = modified;
292 * update the document with new roots.
293 * LATER: decide: this affects the next call to getVamsasRoots()
294 * @see org.vamsas.IClientDocument.setVamsasRoots
296 public void setVamsasRoots(VAMSAS[] newroots) {
298 log.debug("setVamsasRoots called on null document.");
302 if (newroots==null) {
303 log.debug("setVamsasRoots(null) - do nothing.");
306 // are we dealing with same array ?
307 if (_VamsasRoots!=newroots) {
308 // merge roots into local version.
309 newr = new VAMSAS[newroots.length];
310 for (int i=0;i<newr.length;i++)
311 newr[i] = newroots[i];
312 newr=_combineRoots(newr,_VamsasRoots,this);
314 newr = new VAMSAS[_VamsasRoots.length];
315 for (int i=0;i<newr.length;i++)
316 newr[i]=_VamsasRoots[i];
318 // actually compare with document root set for final combination (to ensure nothing is lost)
319 _VamsasRoots = _combineRoots(newr, doc.getVAMSAS(), this);
324 * LATER: decide: this affects the next call to getVamsasRoots()
325 * @see uk.ac.vamsas.client.IClientDocument#addVamsasRoot(uk.ac.vamsas.objects.core.VAMSAS)
327 public void addVamsasRoot(VAMSAS newroot) {
329 log.debug("addVamsasRoots called on null document.");
332 VAMSAS[] newroots = _combineRoots(new VAMSAS[] {newroot}, getVamsasRoots(), this);
333 _VamsasRoots = newroots;
339 * @see uk.ac.vamsas.client.IClientDocument#registerObjects(uk.ac.vamsas.client.Vobject[])
341 public VorbaId[] registerObjects(Vobject[] unregistered) {
343 log.warn("registerObjects[] called on null document.");
346 if (vamsasObjects==null) {
347 log.warn("registerObjects[] called for null vamsasObjects hasharray.");
350 if (unregistered!=null) {
351 VorbaId ids[] = new VorbaId[unregistered.length];
352 for (int i=0,k=unregistered.length; i<k; i++)
353 if (unregistered[i]!=null) {
354 log.warn("Null Vobject passed to registerObject[] at position "+i);
357 ids[i]=registerObject(unregistered[i]);
359 log.debug("Registered "+unregistered.length+" objects - total of "+vamsasObjects.size()+" ids.");
365 * @see uk.ac.vamsas.client.IClientDocument#registerObject(uk.ac.vamsas.client.Vobject)
367 public VorbaId registerObject(Vobject unregistered) {
369 log.warn("registerObjects called on null document.");
372 if (vamsasObjects==null) {
373 log.warn("registerObjects called for null vamsasObjects hasharray.");
376 if (iohandler==null) {
377 log.warn("registerObjects called for read only document.");
381 if (unregistered!=null) {
382 VorbaId id = _registerObject(unregistered);
383 log.debug("Registered object - total of "+vamsasObjects.size()+" ids.");
386 log.warn("Null Vobject passed to registerObject.");
390 * IClientAppdata instance - if it exists.
392 SimpleClientAppdata scappd = null;
394 * @see uk.ac.vamsas.client.IClientDocument#getClientAppdata()
396 public IClientAppdata getClientAppdata() {
397 // TODO: getClientAppdata not tested in ArchiveClient mockup
398 log.error("TODO: TEST Client Appdata access methods");
400 log.warn("getClientAppdata called on null document.");
404 log.debug("Creating new SimpleClientAppdata instance for "+sclient.getSessionHandle());
405 scappd = new SimpleClientAppdata(this);
407 // LATER: may not need this as a warning message.
408 log.warn("Null appdata object for "+sclient.getSessionHandle());
410 log.debug("Created SimpleClientAppdata successfully.");
413 log.debug("Returning existing SimpleClientAppdata reference.");
418 * access the vamsas document
419 * @return the session's vamsas document
421 protected VamsasDocument getVamsasDocument() {
425 * returns the read-only IO interface for the vamsas document Jar file
428 protected VamsasArchiveReader getVamsasArchiveReader() {
429 if (iohandler==null) {
430 log.error("Near fatal. Null VamsasArchive iohandler so can't get VamsasArchiveReader");
434 log.info("TODO: test getVamsasArchiveReader");
435 return iohandler.getOriginalArchiveReader();
436 } catch (Exception e) {
437 log.warn("Unable to create OriginalArchiveReader!", e);
442 * called by vamsas api to write updated document to session
443 * @return true if update was successful
444 * @throws java.io.IOException
446 protected boolean updateSessionDocument() throws java.io.IOException {
447 boolean docupdate = true; // 'non-serious' problems below set this false
449 log.warn("updateSessionDocument called on null document.");
450 throw new java.io.IOException("Document is closed.");
452 if (iohandler==null) {
453 log.warn("updateSessionDocument called document iohandler handler.");
454 throw new java.io.IOException("Document is closed.");
457 if (!isModified() && !scappd.isModified()) {
458 log.debug("Document update not necessary. returning false.");
461 VamsasSession session = sclient._session;
462 log.debug("updating Session Document in "+session.sessionDir);
463 // update the VamsasDocument structure with any new appData's.
464 // try to update the sessionFile
465 log.debug("Attempting to update session "+sclient.session.getSessionUrn());
466 if (scappd!=null && scappd.isModified()) {
467 ClientHandle client = sclient.client;
468 UserHandle user = sclient.user;
469 scappd.closeForWriting();
470 if (scappd.appsGlobal==null) {
471 log.debug("Creating new appData entry for this application...");
472 // first write for this application - add a new section in document
473 ApplicationData appd = scappd.appsGlobal = new ApplicationData();
474 appd.setName(client.getClientName());
475 // appd.setUrn(client.getClientUrn());
476 appd.setVersion(client.getVersion());
477 doc.addApplicationData(appd);
478 // embed or jarEntry ? - for now only jarEntry's are dealt with.
479 appd.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()));
480 log.debug("... created.");
482 if (scappd.newAppData!=null && scappd.newAppData.sessionFile.exists()) {
483 log.debug("Beginning update for new Global Appdata...");
484 // new global appdata to write.
485 if (scappd.appsGlobal.getData()!=null) {
486 scappd.appsGlobal.setData(null);
487 scappd.appsGlobal.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()));
489 // LATER: use a switch to decide if the data should be written as a reference or as an embedded data chunk
490 scappd.updateAnAppdataEntry(iohandler, scappd.appsGlobal, scappd.newAppData);
491 log.debug("...Successfully updated Global Appdata Entry.");
493 if (scappd.newUserData!=null && scappd.newUserData.sessionFile.exists()) {
494 log.debug("Beginning to update Users Appdata entry....");
495 if (scappd.usersData==null) {
496 // create new user appdata
497 scappd.usersData = new User();
498 scappd.usersData.setFullname(user.getFullName());
499 scappd.usersData.setOrganization(user.getOrganization());
500 scappd.appsGlobal.addUser(scappd.usersData);
502 User appd = scappd.usersData;
503 if (appd.getData()!=null || appd.getDataReference()==null) {
504 // LATER make standard appDataReference constructor for client+user
506 String safe_username = user.getFullName();
507 int t = safe_username.indexOf(" ");
509 safe_username = safe_username.substring(t);
511 appd.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()+safe_username));
513 scappd.updateAnAppdataEntry(iohandler, scappd.usersData, scappd.newUserData);
514 log.debug("...Successfully updated user AppData entry.");
518 if (iohandler.transferRemainingAppDatas())
519 log.debug("Remaining appdatas were transferred.");
521 log.debug("No remaining appdatas were transferred. (Correct?)");
522 } catch (Exception e) {
523 log.error("While transferring remaining AppDatas", e);
525 log.debug("Updating Document...");
526 // now update the document. - this was basically the doUpdate method in test.ArchiveClient
527 updateDocumentRoots();
529 iohandler.putVamsasDocument(doc);
530 log.debug("Successfully written document entry.");
532 catch (Exception e) {
533 log.error("Marshalling error for vamsas document.",e);
534 docupdate = false; // pass on the (probable) object validation error
536 iohandler.closeArchive();
537 iohandler=null; // so this method cannot be called again for this instance
538 log.debug("...successully finished and closed.");
539 return docupdate; // no errors ?
542 * @see java.lang.Object#finalize()
544 protected void finalize() throws Throwable {
545 log.debug("Garbage collecting on ClientDocument instance.");
553 // disengage from client
555 sclient.cdocument = null;
560 public Vector getUpdatedObjects() {
561 // TODO: WALK through the document objects calling the update mechanism for each one, or just pass this vector back to client ?return updatedObjects;