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;
11 import org.vamsas.objects.utils.AppDataReference;
12 import org.vamsas.test.objects.Core;
14 import uk.ac.vamsas.client.ClientHandle;
15 import uk.ac.vamsas.client.IClientAppdata;
16 import uk.ac.vamsas.client.IClientDocument;
17 import uk.ac.vamsas.client.UserHandle;
18 import uk.ac.vamsas.client.Vobject;
19 import uk.ac.vamsas.client.VorbaId;
20 import uk.ac.vamsas.objects.core.ApplicationData;
21 import uk.ac.vamsas.objects.core.User;
22 import uk.ac.vamsas.objects.core.VAMSAS;
23 import uk.ac.vamsas.objects.core.VamsasDocument;
26 * Maintains a collection of vamsas objects, appdatas and states, and provides api for a SimpleClient's client.
29 public class ClientDocument extends uk.ac.vamsas.client.ClientDocument implements IClientDocument {
30 private static Log log = LogFactory.getLog(ClientDocument.class);
31 private VamsasDocument doc;
32 protected SimpleClient sclient;
33 protected VamsasArchive archive = null;
35 * indicate if new data has been incorporated
37 private boolean isModified = false;
39 * Public method for internal use by SimpleClient.
40 * @return true if document has been modified.
42 public boolean isModified() {
45 private Vector updatedObjects=null;
48 * prepare Application-side dataset from the vamsas Document archive
49 * @param doc - the dataset
50 * @param docHandler - the sessionFile IO handler
51 * @param Factory - the source of current and new vorbaIds
52 * @param sclient - the simpleclient instance
54 protected ClientDocument(VamsasDocument doc, VamsasArchive docHandler, IdFactory Factory, SimpleClient sclient) {
55 super(Factory.getVorbaIdHash(), Factory);
59 * prepare Application-side dataset from the vamsas Document archive
61 this.sclient = sclient;
64 updatedObjects=null; /// TODO: correct this line
70 * @see uk.ac.vamsas.client.IClientDocument#getObject(uk.ac.vamsas.client.VorbaId)
72 public Vobject getObject(VorbaId id) {
73 if (vamsasObjects==null) {
74 log.debug("getObject called on null objrefs list.");
77 if (vamsasObjects.containsKey(id))
78 return (Vobject) vamsasObjects.get(id);
79 log.debug("Returning null Vobject reference for id "+id.getId());
86 * @see uk.ac.vamsas.client.IClientDocument#getObjects(uk.ac.vamsas.client.VorbaId[])
88 public Vobject[] getObjects(VorbaId[] ids) {
89 if (vamsasObjects==null) {
90 log.debug("getObject[] called on null vamsasObjects list.");
93 Vobject[] vo = new Vobject[ids.length];
94 for (int i=0,j=ids.length; i<j;i++)
95 if (vamsasObjects.containsKey(ids[i]))
96 vo[i] = (Vobject) vamsasObjects.get(ids[i]);
98 log.debug("Returning null Vobject reference for id "+ids[i].getId());
102 * internal reference to single copy of Document Roots array
104 private VAMSAS[] _VamsasRoots=null;
107 * 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)
108 * @see uk.ac.vamsas.client.IClientDocument#getVamsasRoots()
110 public VAMSAS[] getVamsasRoots() {
112 log.debug("Null document for getVamsasRoots(), returning null");
116 // LATER: decide on read-only status of ClientDocument object
117 log.warn("getVamsasRoots() called on possibly read-only document.");
119 if (_VamsasRoots!=null)
121 VAMSAS[] roots = doc.getVAMSAS();
123 // Make a new one to return to client to get filled.
124 _VamsasRoots = new VAMSAS[] { new VAMSAS() };
125 // Do provenance now. just in case.
126 doc.getProvenance().addEntry(sclient.getProvenanceEntry("Created new document root [id="+_VamsasRoots[0].getId()+"]"));
127 doc.addVAMSAS(_VamsasRoots[0]);
129 _VamsasRoots = new VAMSAS[roots.length];
130 for (int r=0;r<roots.length; r++)
131 _VamsasRoots[r] = roots[r];
136 private int _contains(VAMSAS root, VAMSAS[] docRoots) {
139 if (docRoots==null || docRoots.length==0)
141 String r_id = root.getId();
142 for (int i=0,j=docRoots.length; i<j; i++)
143 if (docRoots[i]==root || (docRoots[i]!=null && docRoots[i].getId().equals(r_id)))
148 * verify that newr version is really an intact version of the
149 * @param newVersion (may be modified)
151 * @return true if newVersion is a valid root that preserves original references
153 private boolean isValidUpdate(VAMSAS newVersion, final VAMSAS oldVersion) {
154 // ideal - this cascades down the two structures, ensuring that all ID'd objects in one are present in the other.
155 if (oldVersion==newVersion) {
156 // may be a virgin root element.
157 if (!newVersion.isRegistered())
158 _registerObject(newVersion);
159 // Should retrieve original version and compare - unless local hashes can be used to determine if resultSet has been truncated.
160 // just do internal validation for moment.
161 if (newVersion.isValid())
165 // redundant ? if (oldVersion.is__stored_in_document())
166 if (!newVersion.isRegistered())
167 _registerObject(newVersion);
168 if (newVersion.isValid())
173 * LATER isValidUpdate : Ideally. we efficiently walk down, comparing hashes, to deal with merging and verifying provenance for objects
175 // extract root objects
176 if (newroots != null) {
177 // check newroots for objects that were present in the old document
178 // check to see if the 'old' objects have been modified
179 // if they have ? we overwrite them with their new version, ensuring that
180 // provenance is updated.
181 // if they haven't ? do nothing ?
183 for (int i = 0, k = newroots.length; i < k; i++) {
184 if (newroots[i].isRegistered()) {
185 // easy - just check if anything has changed and do provenance
186 Vobject oldversion = getObject(newroots[i].getVorbaId());
187 if (oldversion instanceof VAMSAS) {
188 // LATER: appropriate merging behaviour when two clients have improperly modified the same Vobject independently.
189 if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
190 // client has modified this Vobject since last retrieval.
191 if (newroots[i].get__last_hash() != oldversion.get__last_hash()) {
192 // Vobject has been modified by another client since this
194 // last access to document.
199 "SimpleClient error when using setVamsasRoots : The vorbaId for Vobject "
201 + " does not refer to an Vobject of type VAMSAS in the current document!");
204 if (!newroots[i].is__stored_in_document()) {
205 // check if Vobject is modified
206 if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
207 // it is - so we add newroots[i] as a new Vobject, with updated
214 // just add newroots[i] as a new Vobject in the document
215 // - with appropriate provenance.
221 * merge old and new root vectors
222 * @param newr This array may be written to
224 * @param the client document (usually this) which this root set belongs to.
225 * @return merged vector of vamsas roots
227 private VAMSAS[] _combineRoots(VAMSAS[] newr, final VAMSAS[] original, ClientDocument modflag) {
228 Vector rts = new Vector();
229 boolean modified=false;
230 for (int i=0,j=original.length; i<j; i++) {
231 int k = _contains(original[i], newr);
233 if (isValidUpdate(newr[k], original[i])) {
238 // LATER: try harder to merge ducument roots.
239 log.warn("Couldn't merge new VAMSAS root "+newr[k].getId());
240 newr[k] = null; // LATER: this means we ignore mangled roots. NOT GOOD
244 rts.add(original[i]);
247 // add remaining (new) roots
248 for (int i=0,j=newr.length; i<j; i++) {
254 newr = new VAMSAS[rts.size()];
255 for (int i=0,j=rts.size(); i<j; i++)
256 newr[i] = (VAMSAS) rts.get(i);
258 modflag.isModified = modified;
263 * update the document with new roots.
264 * LATER: decide: this affects the next call to getVamsasRoots()
265 * @see org.vamsas.IClientDocument.setVamsasRoots
267 public void setVamsasRoots(VAMSAS[] newroots) {
269 log.debug("setVamsasRoots called on null document.");
273 if (newroots==null) {
274 log.debug("setVamsasRoots(null) - do nothing.");
277 // are we dealing with same array ?
278 if (_VamsasRoots!=newroots) {
279 // merge roots into local version.
280 newr = new VAMSAS[newroots.length];
281 for (int i=0;i<newr.length;i++)
282 newr[i] = newroots[i];
283 newr=_combineRoots(newr,_VamsasRoots,this);
285 newr = new VAMSAS[_VamsasRoots.length];
286 for (int i=0;i<newr.length;i++)
287 newr[i]=_VamsasRoots[i];
289 // actually compare with document root set for final combination (to ensure nothing is lost)
290 _VamsasRoots = _combineRoots(newr, doc.getVAMSAS(), this);
295 * LATER: decide: this affects the next call to getVamsasRoots()
296 * @see uk.ac.vamsas.client.IClientDocument#addVamsasRoot(uk.ac.vamsas.objects.core.VAMSAS)
298 public void addVamsasRoot(VAMSAS newroot) {
300 log.debug("addVamsasRoots called on null document.");
303 VAMSAS[] newroots = _combineRoots(new VAMSAS[] {newroot}, _VamsasRoots, this);
304 _VamsasRoots = newroots;
310 * @see uk.ac.vamsas.client.IClientDocument#registerObjects(uk.ac.vamsas.client.Vobject[])
312 public VorbaId[] registerObjects(Vobject[] unregistered) {
314 log.warn("registerObjects[] called on null document.");
317 if (vamsasObjects==null) {
318 log.warn("registerObjects[] called for null vamsasObjects hasharray.");
321 if (unregistered!=null) {
322 VorbaId ids[] = new VorbaId[unregistered.length];
323 for (int i=0,k=unregistered.length; i<k; i++)
324 if (unregistered[i]!=null) {
325 log.warn("Null Vobject passed to registerObject[] at position "+i);
328 ids[i]=registerObject(unregistered[i]);
330 log.debug("Registered "+unregistered.length+" objects - total of "+vamsasObjects.size()+" ids.");
336 * @see uk.ac.vamsas.client.IClientDocument#registerObject(uk.ac.vamsas.client.Vobject)
338 public VorbaId registerObject(Vobject unregistered) {
340 log.warn("registerObjects called on null document.");
343 if (vamsasObjects==null) {
344 log.warn("registerObjects called for null vamsasObjects hasharray.");
347 if (unregistered!=null) {
348 VorbaId id = _registerObject(unregistered);
349 log.debug("Registered object - total of "+vamsasObjects.size()+" ids.");
352 log.warn("Null Vobject passed to registerObject.");
356 * IClientAppdata instance - if it exists.
358 SimpleClientAppdata scappd = null;
360 * @see uk.ac.vamsas.client.IClientDocument#getClientAppdata()
362 public IClientAppdata getClientAppdata() {
364 log.warn("getClientAppdata called on null document.");
368 log.debug("Creating new SimpleClientAppdata instance for "+sclient.getSessionHandle());
369 scappd = new SimpleClientAppdata(this);
371 // LATER: may not need this as a warning message.
372 log.warn("Null appdata object for "+sclient.getSessionHandle());
374 log.debug("Created SimpleClientAppdata successfully.");
377 log.debug("Returning existing SimpleClientAppdata reference.");
382 * access the vamsas document
383 * @return the session's vamsas document
385 protected VamsasDocument getVamsasDocument() {
389 * returns the read-only IO interface for the vamsas document Jar file
392 protected VamsasArchiveReader getVamsasArchiveReader() {
394 return archive.getOriginalArchiveReader();
395 } catch (Exception e) {
396 log.warn("Unable to create OriginalArchiveReader!", e);
400 protected boolean updateSessionDocument() throws java.io.IOException {
401 boolean docupdate = true; // 'non-serious' problems below set this false
403 log.warn("updateSessionDocument called on null document.");
404 throw new java.io.IOException("Document is closed.");
407 log.warn("updateSessionDocument called document archive handler.");
408 throw new java.io.IOException("Document is closed.");
411 if (!isModified() && !scappd.isModified()) {
412 log.debug("Document update not necessary. returning false.");
415 VamsasSession session = sclient._session;
416 log.debug("updating Session Document in "+session.sessionDir);
417 // update the VamsasDocument structure with any new appData's.
418 // try to update the sessionFile
419 log.debug("Attempting to update session "+sclient.session.getSessionUrn());
420 if (scappd.isModified()) {
421 ClientHandle client = sclient.client;
422 UserHandle user = sclient.user;
423 scappd.closeForWriting();
424 if (scappd.appsGlobal==null) {
425 log.debug("Creating new appData entry for this application...");
426 // first write for this application - add a new section in document
427 ApplicationData appd = scappd.appsGlobal = new ApplicationData();
428 appd.setName(client.getClientName());
429 // appd.setUrn(client.getClientUrn());
430 appd.setVersion(client.getVersion());
431 doc.addApplicationData(appd);
432 // embed or jarEntry ? - for now only jarEntry's are dealt with.
433 appd.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()));
434 log.debug("... created.");
436 if (scappd.newAppData!=null && scappd.newAppData.sessionFile.exists()) {
437 log.debug("Beginning update for new Global Appdata...");
438 // new global appdata to write.
439 if (scappd.appsGlobal.getData()!=null) {
440 scappd.appsGlobal.setData(null);
441 scappd.appsGlobal.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()));
443 // LATER: use a switch to decide if the data should be written as a reference or as an embedded data chunk
444 scappd.updateAnAppdataEntry(archive, scappd.appsGlobal, scappd.newAppData);
445 log.debug("...Successfully updated Global Appdata Entry.");
447 if (scappd.newUserData!=null && scappd.newUserData.sessionFile.exists()) {
448 log.debug("Beginning to update Users Appdata entry....");
449 if (scappd.usersData==null) {
450 // create new user appdata
451 scappd.usersData = new User();
452 scappd.usersData.setFullname(user.getFullName());
453 scappd.usersData.setOrganization(user.getOrganization());
454 scappd.appsGlobal.addUser(scappd.usersData);
456 User appd = scappd.usersData;
457 if (appd.getData()!=null || appd.getDataReference()==null) {
458 // LATER make standard appDataReference constructor for client+user
460 String safe_username = user.getFullName();
461 int t = safe_username.indexOf(" ");
463 safe_username = safe_username.substring(t);
465 appd.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()+safe_username));
467 scappd.updateAnAppdataEntry(archive, scappd.usersData, scappd.newUserData);
468 log.debug("...Successfully updated user AppData entry.");
471 log.debug("Updating Document...");
472 // now update the document.
474 archive.putVamsasDocument(doc);
475 log.debug("Successfully written document entry.");
477 catch (Exception e) {
478 log.error("Marshalling error for vamsas document.",e);
479 docupdate = false; // pass on the (probable) object validation error
481 if (archive.transferRemainingAppDatas())
482 log.debug("Remaining appdatas were transferred.");
484 log.debug("No remaining appdatas were transferred. (Correct?)");
485 archive.closeArchive();
486 log.debug("...successully finished and closed.");
487 return docupdate; // no errors ?
490 * @see java.lang.Object#finalize()
492 protected void finalize() throws Throwable {
493 log.debug("Garbage collecting on ClientDocument instance.");
501 // disengage from client
503 sclient.cdocument = null;
508 public Vector getUpdatedObjects() {
509 return updatedObjects;