4 package org.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.client.ClientHandle;
12 import org.vamsas.client.IClientAppdata;
13 import org.vamsas.client.IClientDocument;
14 import org.vamsas.client.UserHandle;
15 import org.vamsas.client.Vobject;
16 import org.vamsas.client.VorbaId;
17 import org.vamsas.objects.core.ApplicationData;
18 import org.vamsas.objects.core.User;
19 import org.vamsas.objects.core.VAMSAS;
20 import org.vamsas.objects.core.VamsasDocument;
21 import org.vamsas.objects.utils.AppDataReference;
22 import org.vamsas.test.objects.Core;
25 * Maintains a collection of vamsas objects, appdatas and states, and provides api for a SimpleClient's client.
28 public class ClientDocument extends org.vamsas.client.ClientDocument implements IClientDocument {
29 private static Log log = LogFactory.getLog(ClientDocument.class);
30 private VamsasDocument doc;
31 protected SimpleClient sclient;
32 protected VamsasArchive archive = null;
34 * indicate if new data has been incorporated
36 private boolean isModified = false;
38 * Public method for internal use by SimpleClient.
39 * @return true if document has been modified.
41 public boolean isModified() {
44 private java.util.Hashtable objrefs=null;
47 * prepare Application-side dataset from the vamsas Document archive
48 * @param doc - the dataset
49 * @param docHandler - the sessionFile IO handler
50 * @param Factory - the source of current and new vorbaIds
51 * @param sclient - the simpleclient instance
53 protected ClientDocument(VamsasDocument doc, VamsasArchive docHandler, IdFactory Factory, SimpleClient sclient) {
54 super(Factory.getVorbaIdHash(), Factory);
57 * prepare Application-side dataset from the vamsas Document archive
59 this.sclient = sclient;
62 objrefs = Factory.getVorbaIdHash();
68 * @see org.vamsas.client.IClientDocument#getObject(org.vamsas.client.VorbaId)
70 public Vobject getObject(VorbaId id) {
72 log.debug("getObject called on null objrefs list.");
75 if (objrefs.containsKey(id))
76 return (Vobject) objrefs.get(id);
77 log.debug("Returning null Vobject reference for id "+id.getId());
84 * @see org.vamsas.client.IClientDocument#getObjects(org.vamsas.client.VorbaId[])
86 public Vobject[] getObjects(VorbaId[] ids) {
88 log.debug("getObject[] called on null objrefs list.");
91 Vobject[] vo = new Vobject[ids.length];
92 for (int i=0,j=ids.length; i<j;i++)
93 if (objrefs.containsKey(ids[i]))
94 vo[i] = (Vobject) objrefs.get(ids[i]);
96 log.debug("Returning null Vobject reference for id "+ids[i].getId());
100 * internal reference to single copy of Document Roots array
102 private VAMSAS[] _VamsasRoots=null;
105 * 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)
106 * @see org.vamsas.client.IClientDocument#getVamsasRoots()
108 public VAMSAS[] getVamsasRoots() {
110 log.debug("Null document for getVamsasRoots(), returning null");
114 // LATER: decide on read-only status of ClientDocument object
115 log.warn("getVamsasRoots() called on possibly read-only document.");
117 if (_VamsasRoots!=null)
119 VAMSAS[] roots = doc.getVAMSAS();
121 // Make a new one to return to client to get filled.
122 _VamsasRoots = new VAMSAS[] { new VAMSAS() };
123 // Do provenance now. just in case.
124 doc.getProvenance().addEntry(sclient.getProvenanceEntry("Created new document root [id="+_VamsasRoots[0].getId()+"]"));
125 doc.addVAMSAS(_VamsasRoots[0]);
127 _VamsasRoots = new VAMSAS[roots.length];
128 for (int r=0;r<roots.length; r++)
129 _VamsasRoots[r] = roots[r];
134 private int _contains(VAMSAS root, VAMSAS[] docRoots) {
137 if (docRoots==null || docRoots.length==0)
139 String r_id = root.getId();
140 for (int i=0,j=docRoots.length; i<j; i++)
141 if (docRoots[i]==root || (docRoots[i]!=null && docRoots[i].getId().equals(r_id)))
146 * verify that newr version is really an intact version of the
147 * @param newVersion (may be modified)
149 * @return true if newVersion is a valid root that preserves original references
151 private boolean isValidUpdate(VAMSAS newVersion, final VAMSAS oldVersion) {
152 // ideal - this cascades down the two structures, ensuring that all ID'd objects in one are present in the other.
153 if (oldVersion==newVersion) {
154 // may be a virgin root element.
155 if (!newVersion.isRegistered())
156 _registerObject(newVersion);
157 // Should retrieve original version and compare - unless local hashes can be used to determine if resultSet has been truncated.
158 // just do internal validation for moment.
159 if (newVersion.isValid())
163 // redundant ? if (oldVersion.is__stored_in_document())
164 if (!newVersion.isRegistered())
165 _registerObject(newVersion);
166 if (newVersion.isValid())
171 * LATER isValidUpdate : Ideally. we efficiently walk down, comparing hashes, to deal with merging and verifying provenance for objects
173 // extract root objects
174 if (newroots != null) {
175 // check newroots for objects that were present in the old document
176 // check to see if the 'old' objects have been modified
177 // if they have ? we overwrite them with their new version, ensuring that
178 // provenance is updated.
179 // if they haven't ? do nothing ?
181 for (int i = 0, k = newroots.length; i < k; i++) {
182 if (newroots[i].isRegistered()) {
183 // easy - just check if anything has changed and do provenance
184 Vobject oldversion = getObject(newroots[i].getVorbaId());
185 if (oldversion instanceof VAMSAS) {
186 // LATER: appropriate merging behaviour when two clients have improperly modified the same Vobject independently.
187 if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
188 // client has modified this Vobject since last retrieval.
189 if (newroots[i].get__last_hash() != oldversion.get__last_hash()) {
190 // Vobject has been modified by another client since this
192 // last access to document.
197 "SimpleClient error when using setVamsasRoots : The vorbaId for Vobject "
199 + " does not refer to an Vobject of type VAMSAS in the current document!");
202 if (!newroots[i].is__stored_in_document()) {
203 // check if Vobject is modified
204 if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
205 // it is - so we add newroots[i] as a new Vobject, with updated
212 // just add newroots[i] as a new Vobject in the document
213 // - with appropriate provenance.
219 * merge old and new root vectors
220 * @param newr This array may be written to
222 * @param the client document (usually this) which this root set belongs to.
223 * @return merged vector of vamsas roots
225 private VAMSAS[] _combineRoots(VAMSAS[] newr, final VAMSAS[] original, ClientDocument modflag) {
226 Vector rts = new Vector();
227 boolean modified=false;
228 for (int i=0,j=original.length; i<j; i++) {
229 int k = _contains(original[i], newr);
231 if (isValidUpdate(newr[k], original[i])) {
236 // LATER: try harder to merge ducument roots.
237 log.warn("Couldn't merge new VAMSAS root "+newr[k].getId());
238 newr[k] = null; // LATER: this means we ignore mangled roots. NOT GOOD
242 rts.add(original[i]);
245 // add remaining (new) roots
246 for (int i=0,j=newr.length; i<j; i++) {
252 newr = new VAMSAS[rts.size()];
253 for (int i=0,j=rts.size(); i<j; i++)
254 newr[i] = (VAMSAS) rts.get(i);
256 modflag.isModified = modified;
261 * update the document with new roots.
262 * LATER: decide: this affects the next call to getVamsasRoots()
263 * @see org.vamsas.IClientDocument.setVamsasRoots
265 public void setVamsasRoots(VAMSAS[] newroots) {
267 log.debug("setVamsasRoots called on null document.");
271 if (newroots==null) {
272 log.debug("setVamsasRoots(null) - do nothing.");
275 // are we dealing with same array ?
276 if (_VamsasRoots!=newroots) {
277 // merge roots into local version.
278 newr = new VAMSAS[newroots.length];
279 for (int i=0;i<newr.length;i++)
280 newr[i] = newroots[i];
281 newr=_combineRoots(newr,_VamsasRoots,this);
283 newr = new VAMSAS[_VamsasRoots.length];
284 for (int i=0;i<newr.length;i++)
285 newr[i]=_VamsasRoots[i];
287 // actually compare with document root set for final combination (to ensure nothing is lost)
288 _VamsasRoots = _combineRoots(newr, doc.getVAMSAS(), this);
293 * LATER: decide: this affects the next call to getVamsasRoots()
294 * @see org.vamsas.client.IClientDocument#addVamsasRoot(org.vamsas.objects.core.VAMSAS)
296 public void addVamsasRoot(VAMSAS newroot) {
298 log.debug("addVamsasRoots called on null document.");
301 VAMSAS[] newroots = _combineRoots(new VAMSAS[] {newroot}, _VamsasRoots, this);
302 _VamsasRoots = newroots;
308 * @see org.vamsas.client.IClientDocument#registerObjects(org.vamsas.client.Vobject[])
310 public VorbaId[] registerObjects(Vobject[] unregistered) {
312 log.warn("registerObjects[] called on null document.");
316 log.warn("registerObjects[] called for null objrefs hasharray.");
319 if (unregistered!=null) {
320 VorbaId ids[] = new VorbaId[unregistered.length];
321 for (int i=0,k=unregistered.length; i<k; i++)
322 if (unregistered[i]!=null) {
323 log.warn("Null Vobject passed to registerObject[] at position "+i);
326 ids[i]=registerObject(unregistered[i]);
328 log.debug("Registered "+unregistered.length+" objects - total of "+objrefs.size()+" ids.");
334 * @see org.vamsas.client.IClientDocument#registerObject(org.vamsas.client.Vobject)
336 public VorbaId registerObject(Vobject unregistered) {
338 log.warn("registerObjects called on null document.");
342 log.warn("registerObjects called for null objrefs hasharray.");
345 if (unregistered!=null) {
346 VorbaId id = _registerObject(unregistered);
347 log.debug("Registered object - total of "+objrefs.size()+" ids.");
350 log.warn("Null Vobject passed to registerObject.");
354 * IClientAppdata instance - if it exists.
356 SimpleClientAppdata scappd = null;
358 * @see org.vamsas.client.IClientDocument#getClientAppdata()
360 public IClientAppdata getClientAppdata() {
362 log.warn("getClientAppdata called on null document.");
366 log.debug("Creating new SimpleClientAppdata instance for "+sclient.getSessionHandle());
367 scappd = new SimpleClientAppdata(this);
369 // LATER: may not need this as a warning message.
370 log.warn("Null appdata object for "+sclient.getSessionHandle());
372 log.debug("Created SimpleClientAppdata successfully.");
375 log.debug("Returning existing SimpleClientAppdata reference.");
380 * access the vamsas document
381 * @return the session's vamsas document
383 protected VamsasDocument getVamsasDocument() {
387 * returns the read-only IO interface for the vamsas document Jar file
390 protected VamsasArchiveReader getVamsasArchiveReader() {
392 return archive.getOriginalArchiveReader();
393 } catch (Exception e) {
394 log.warn("Unable to create OriginalArchiveReader!", e);
398 protected boolean updateSessionDocument() throws java.io.IOException {
399 boolean docupdate = true; // 'non-serious' problems below set this false
401 log.warn("updateSessionDocument called on null document.");
402 throw new java.io.IOException("Document is closed.");
405 log.warn("updateSessionDocument called document archive handler.");
406 throw new java.io.IOException("Document is closed.");
409 if (!isModified() && !scappd.isModified()) {
410 log.debug("Document update not necessary. returning false.");
413 VamsasSession session = sclient._session;
414 log.debug("updating Session Document in "+session.sessionDir);
415 // update the VamsasDocument structure with any new appData's.
416 // try to update the sessionFile
417 log.debug("Attempting to update session "+sclient.session.getSessionUrn());
418 if (scappd.isModified()) {
419 ClientHandle client = sclient.client;
420 UserHandle user = sclient.user;
421 scappd.closeForWriting();
422 if (scappd.appsGlobal==null) {
423 log.debug("Creating new appData entry for this application...");
424 // first write for this application - add a new section in document
425 ApplicationData appd = scappd.appsGlobal = new ApplicationData();
426 appd.setName(client.getClientName());
427 appd.setUrn(client.getClientUrn());
428 appd.setVersion(client.getVersion());
429 doc.addApplicationData(appd);
430 // embed or jarEntry ? - for now only jarEntry's are dealt with.
431 appd.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()));
432 log.debug("... created.");
434 if (scappd.newAppData!=null && scappd.newAppData.sessionFile.exists()) {
435 log.debug("Beginning update for new Global Appdata...");
436 // new global appdata to write.
437 if (scappd.appsGlobal.getData()!=null) {
438 scappd.appsGlobal.setData(null);
439 scappd.appsGlobal.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()));
441 // LATER: use a switch to decide if the data should be written as a reference or as an embedded data chunk
442 scappd.updateAnAppdataEntry(archive, scappd.appsGlobal, scappd.newAppData);
443 log.debug("...Successfully updated Global Appdata Entry.");
445 if (scappd.newUserData!=null && scappd.newUserData.sessionFile.exists()) {
446 log.debug("Beginning to update Users Appdata entry....");
447 if (scappd.usersData==null) {
448 // create new user appdata
449 scappd.usersData = new User();
450 scappd.usersData.setFullname(user.getFullName());
451 scappd.usersData.setOrganization(user.getOrganization());
452 scappd.appsGlobal.addUser(scappd.usersData);
454 User appd = scappd.usersData;
455 if (appd.getData()!=null || appd.getDataReference()==null) {
456 // LATER make standard appDataReference constructor for client+user
458 String safe_username = user.getFullName();
459 int t = safe_username.indexOf(" ");
461 safe_username = safe_username.substring(t);
463 appd.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()+safe_username));
465 scappd.updateAnAppdataEntry(archive, scappd.usersData, scappd.newUserData);
466 log.debug("...Successfully updated user AppData entry.");
469 log.debug("Updating Document...");
470 // now update the document.
472 archive.putVamsasDocument(doc);
473 log.debug("Successfully written document entry.");
475 catch (Exception e) {
476 log.error("Marshalling error for vamsas document.",e);
477 docupdate = false; // pass on the (probable) object validation error
479 if (archive.transferRemainingAppDatas())
480 log.debug("Remaining appdatas were transferred.");
482 log.debug("No remaining appdatas were transferred. (Correct?)");
483 archive.closeArchive();
484 log.debug("...successully finished and closed.");
485 return docupdate; // no errors ?
488 * @see java.lang.Object#finalize()
490 protected void finalize() throws Throwable {
491 log.debug("Garbage collecting on ClientDocument instance.");
499 // disengage from client
501 sclient.cdocument = null;