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))
163 * verify that newr version is really an intact version of the
164 * @param newVersion (may be modified)
166 * @return true if newVersion is a valid root that preserves original references
168 private boolean isValidUpdate(VAMSAS newVersion, final VAMSAS oldVersion) {
169 // ideal - this cascades down the two structures, ensuring that all ID'd objects in one are present in the other.
170 if (oldVersion==newVersion) {
171 // may be a virgin root element.
172 if (!newVersion.isRegistered())
173 _registerObject(newVersion); // TODO: check - this call hasn't been tested.
174 // Should retrieve original version and compare - unless local hashes can be used to determine if resultSet has been truncated.
175 // just do internal validation for moment.
176 if (newVersion.isValid())
180 // redundant ? if (oldVersion.is__stored_in_document())
181 if (!newVersion.isRegistered())
182 _registerObject(newVersion);
183 if (newVersion.isValid())
188 * LATER: MUCH LATER! - not needed for simple case and this routine shouldn't live in this class anymore
189 * isValidUpdate : Ideally. we efficiently walk down, comparing hashes, to deal with merging and verifying provenance for objects
191 // extract root objects
192 if (newroots != null) {
193 // check newroots for objects that were present in the old document
194 // check to see if the 'old' objects have been modified
195 // if they have ? we overwrite them with their new version, ensuring that
196 // provenance is updated.
197 // if they haven't ? do nothing ?
199 for (int i = 0, k = newroots.length; i < k; i++) {
200 if (newroots[i].isRegistered()) {
201 // easy - just check if anything has changed and do provenance
202 Vobject oldversion = getObject(newroots[i].getVorbaId());
203 if (oldversion instanceof VAMSAS) {
204 // LATER: appropriate merging behaviour when two clients have improperly modified the same Vobject independently.
205 if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
206 // client has modified this Vobject since last retrieval.
207 if (newroots[i].get__last_hash() != oldversion.get__last_hash()) {
208 // Vobject has been modified by another client since this
210 // last access to document.
215 "SimpleClient error when using setVamsasRoots : The vorbaId for Vobject "
217 + " does not refer to an Vobject of type VAMSAS in the current document!");
220 if (!newroots[i].is__stored_in_document()) {
221 // check if Vobject is modified
222 if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
223 // it is - so we add newroots[i] as a new Vobject, with updated
230 // just add newroots[i] as a new Vobject in the document
231 // - with appropriate provenance.
237 * merge old and new root vectors
238 * @param newr This array may be written to
240 * @param the client document (usually this) which this root set belongs to.
241 * @return merged vector of vamsas roots
243 private VAMSAS[] _combineRoots(VAMSAS[] newr, final VAMSAS[] original, ClientDocument modflag) {
244 Vector rts = new Vector();
245 boolean modified=false;
246 for (int i=0,j=original.length; i<j; i++) {
247 int k = _contains(original[i], newr);
249 if (isValidUpdate(newr[k], original[i])) {
254 // LATER: try harder to merge ducument roots.
255 log.warn("Couldn't merge new VAMSAS root "+newr[k].getId());
256 newr[k] = null; // LATER: this means we ignore mangled roots. NOT GOOD
260 rts.add(original[i]);
263 // add remaining (new) roots
264 for (int i=0,j=newr.length; i<j; i++) {
270 newr = new VAMSAS[rts.size()];
271 for (int i=0,j=rts.size(); i<j; i++)
272 newr[i] = (VAMSAS) rts.get(i);
274 modflag.isModified = modified;
279 * update the document with new roots.
280 * LATER: decide: this affects the next call to getVamsasRoots()
281 * @see org.vamsas.IClientDocument.setVamsasRoots
283 public void setVamsasRoots(VAMSAS[] newroots) {
285 log.debug("setVamsasRoots called on null document.");
289 if (newroots==null) {
290 log.debug("setVamsasRoots(null) - do nothing.");
293 // are we dealing with same array ?
294 if (_VamsasRoots!=newroots) {
295 // merge roots into local version.
296 newr = new VAMSAS[newroots.length];
297 for (int i=0;i<newr.length;i++)
298 newr[i] = newroots[i];
299 newr=_combineRoots(newr,_VamsasRoots,this);
301 newr = new VAMSAS[_VamsasRoots.length];
302 for (int i=0;i<newr.length;i++)
303 newr[i]=_VamsasRoots[i];
305 // actually compare with document root set for final combination (to ensure nothing is lost)
306 _VamsasRoots = _combineRoots(newr, doc.getVAMSAS(), this);
311 * LATER: decide: this affects the next call to getVamsasRoots()
312 * @see uk.ac.vamsas.client.IClientDocument#addVamsasRoot(uk.ac.vamsas.objects.core.VAMSAS)
314 public void addVamsasRoot(VAMSAS newroot) {
316 log.debug("addVamsasRoots called on null document.");
319 VAMSAS[] newroots = _combineRoots(new VAMSAS[] {newroot}, getVamsasRoots(), this);
320 _VamsasRoots = newroots;
326 * @see uk.ac.vamsas.client.IClientDocument#registerObjects(uk.ac.vamsas.client.Vobject[])
328 public VorbaId[] registerObjects(Vobject[] unregistered) {
330 log.warn("registerObjects[] called on null document.");
333 if (vamsasObjects==null) {
334 log.warn("registerObjects[] called for null vamsasObjects hasharray.");
337 if (unregistered!=null) {
338 VorbaId ids[] = new VorbaId[unregistered.length];
339 for (int i=0,k=unregistered.length; i<k; i++)
340 if (unregistered[i]!=null) {
341 log.warn("Null Vobject passed to registerObject[] at position "+i);
344 ids[i]=registerObject(unregistered[i]);
346 log.debug("Registered "+unregistered.length+" objects - total of "+vamsasObjects.size()+" ids.");
352 * @see uk.ac.vamsas.client.IClientDocument#registerObject(uk.ac.vamsas.client.Vobject)
354 public VorbaId registerObject(Vobject unregistered) {
356 log.warn("registerObjects called on null document.");
359 if (vamsasObjects==null) {
360 log.warn("registerObjects called for null vamsasObjects hasharray.");
363 if (iohandler==null) {
364 log.warn("registerObjects called for read only document.");
368 if (unregistered!=null) {
369 VorbaId id = _registerObject(unregistered);
370 log.debug("Registered object - total of "+vamsasObjects.size()+" ids.");
373 log.warn("Null Vobject passed to registerObject.");
377 * IClientAppdata instance - if it exists.
379 SimpleClientAppdata scappd = null;
381 * @see uk.ac.vamsas.client.IClientDocument#getClientAppdata()
383 public IClientAppdata getClientAppdata() {
384 // TODO: getClientAppdata not tested in ArchiveClient mockup
385 log.error("TODO: TEST Client Appdata access methods");
387 log.warn("getClientAppdata called on null document.");
391 log.debug("Creating new SimpleClientAppdata instance for "+sclient.getSessionHandle());
392 scappd = new SimpleClientAppdata(this);
394 // LATER: may not need this as a warning message.
395 log.warn("Null appdata object for "+sclient.getSessionHandle());
397 log.debug("Created SimpleClientAppdata successfully.");
400 log.debug("Returning existing SimpleClientAppdata reference.");
405 * access the vamsas document
406 * @return the session's vamsas document
408 protected VamsasDocument getVamsasDocument() {
412 * returns the read-only IO interface for the vamsas document Jar file
415 protected VamsasArchiveReader getVamsasArchiveReader() {
416 if (iohandler==null) {
417 log.error("Near fatal. Null VamsasArchive iohandler so can't get VamsasArchiveReader");
421 log.info("TODO: test getVamsasArchiveReader");
422 return iohandler.getOriginalArchiveReader();
423 } catch (Exception e) {
424 log.warn("Unable to create OriginalArchiveReader!", e);
428 protected boolean updateSessionDocument() throws java.io.IOException {
429 boolean docupdate = true; // 'non-serious' problems below set this false
431 log.warn("updateSessionDocument called on null document.");
432 throw new java.io.IOException("Document is closed.");
434 if (iohandler==null) {
435 log.warn("updateSessionDocument called document iohandler handler.");
436 throw new java.io.IOException("Document is closed.");
439 if (!isModified() && !scappd.isModified()) {
440 log.debug("Document update not necessary. returning false.");
443 VamsasSession session = sclient._session;
444 log.debug("updating Session Document in "+session.sessionDir);
445 // update the VamsasDocument structure with any new appData's.
446 // try to update the sessionFile
447 log.debug("Attempting to update session "+sclient.session.getSessionUrn());
448 if (scappd!=null && scappd.isModified()) {
449 ClientHandle client = sclient.client;
450 UserHandle user = sclient.user;
451 scappd.closeForWriting();
452 if (scappd.appsGlobal==null) {
453 log.debug("Creating new appData entry for this application...");
454 // first write for this application - add a new section in document
455 ApplicationData appd = scappd.appsGlobal = new ApplicationData();
456 appd.setName(client.getClientName());
457 // appd.setUrn(client.getClientUrn());
458 appd.setVersion(client.getVersion());
459 doc.addApplicationData(appd);
460 // embed or jarEntry ? - for now only jarEntry's are dealt with.
461 appd.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()));
462 log.debug("... created.");
464 if (scappd.newAppData!=null && scappd.newAppData.sessionFile.exists()) {
465 log.debug("Beginning update for new Global Appdata...");
466 // new global appdata to write.
467 if (scappd.appsGlobal.getData()!=null) {
468 scappd.appsGlobal.setData(null);
469 scappd.appsGlobal.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()));
471 // LATER: use a switch to decide if the data should be written as a reference or as an embedded data chunk
472 scappd.updateAnAppdataEntry(iohandler, scappd.appsGlobal, scappd.newAppData);
473 log.debug("...Successfully updated Global Appdata Entry.");
475 if (scappd.newUserData!=null && scappd.newUserData.sessionFile.exists()) {
476 log.debug("Beginning to update Users Appdata entry....");
477 if (scappd.usersData==null) {
478 // create new user appdata
479 scappd.usersData = new User();
480 scappd.usersData.setFullname(user.getFullName());
481 scappd.usersData.setOrganization(user.getOrganization());
482 scappd.appsGlobal.addUser(scappd.usersData);
484 User appd = scappd.usersData;
485 if (appd.getData()!=null || appd.getDataReference()==null) {
486 // LATER make standard appDataReference constructor for client+user
488 String safe_username = user.getFullName();
489 int t = safe_username.indexOf(" ");
491 safe_username = safe_username.substring(t);
493 appd.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()+safe_username));
495 scappd.updateAnAppdataEntry(iohandler, scappd.usersData, scappd.newUserData);
496 log.debug("...Successfully updated user AppData entry.");
500 if (iohandler.transferRemainingAppDatas())
501 log.debug("Remaining appdatas were transferred.");
503 log.debug("No remaining appdatas were transferred. (Correct?)");
504 } catch (Exception e) {
505 log.error("While transferring remaining AppDatas", e);
507 log.debug("Updating Document...");
508 // now update the document. - this was basically the doUpdate method in test.ArchiveClient
509 updateDocumentRoots();
511 iohandler.putVamsasDocument(doc);
512 log.debug("Successfully written document entry.");
514 catch (Exception e) {
515 log.error("Marshalling error for vamsas document.",e);
516 docupdate = false; // pass on the (probable) object validation error
518 iohandler.closeArchive();
519 iohandler=null; // so this method cannot be called again for this instance
520 log.debug("...successully finished and closed.");
521 return docupdate; // no errors ?
524 * @see java.lang.Object#finalize()
526 protected void finalize() throws Throwable {
527 log.debug("Garbage collecting on ClientDocument instance.");
535 // disengage from client
537 sclient.cdocument = null;
542 public Vector getUpdatedObjects() {
543 // TODO: WALK through the document objects calling the update mechanism for each one, or just pass this vector back to client ?return updatedObjects;