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 Vector updatedObjects=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);
58 * prepare Application-side dataset from the vamsas Document archive
60 this.sclient = sclient;
63 updatedObjects=null; /// TODO: correct this line
69 * @see org.vamsas.client.IClientDocument#getObject(org.vamsas.client.VorbaId)
71 public Vobject getObject(VorbaId id) {
72 if (vamsasObjects==null) {
73 log.debug("getObject called on null objrefs list.");
76 if (vamsasObjects.containsKey(id))
77 return (Vobject) vamsasObjects.get(id);
78 log.debug("Returning null Vobject reference for id "+id.getId());
85 * @see org.vamsas.client.IClientDocument#getObjects(org.vamsas.client.VorbaId[])
87 public Vobject[] getObjects(VorbaId[] ids) {
88 if (vamsasObjects==null) {
89 log.debug("getObject[] called on null vamsasObjects list.");
92 Vobject[] vo = new Vobject[ids.length];
93 for (int i=0,j=ids.length; i<j;i++)
94 if (vamsasObjects.containsKey(ids[i]))
95 vo[i] = (Vobject) vamsasObjects.get(ids[i]);
97 log.debug("Returning null Vobject reference for id "+ids[i].getId());
101 * internal reference to single copy of Document Roots array
103 private VAMSAS[] _VamsasRoots=null;
106 * 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)
107 * @see org.vamsas.client.IClientDocument#getVamsasRoots()
109 public VAMSAS[] getVamsasRoots() {
111 log.debug("Null document for getVamsasRoots(), returning null");
115 // LATER: decide on read-only status of ClientDocument object
116 log.warn("getVamsasRoots() called on possibly read-only document.");
118 if (_VamsasRoots!=null)
120 VAMSAS[] roots = doc.getVAMSAS();
122 // Make a new one to return to client to get filled.
123 _VamsasRoots = new VAMSAS[] { new VAMSAS() };
124 // Do provenance now. just in case.
125 doc.getProvenance().addEntry(sclient.getProvenanceEntry("Created new document root [id="+_VamsasRoots[0].getId()+"]"));
126 doc.addVAMSAS(_VamsasRoots[0]);
128 _VamsasRoots = new VAMSAS[roots.length];
129 for (int r=0;r<roots.length; r++)
130 _VamsasRoots[r] = roots[r];
135 private int _contains(VAMSAS root, VAMSAS[] docRoots) {
138 if (docRoots==null || docRoots.length==0)
140 String r_id = root.getId();
141 for (int i=0,j=docRoots.length; i<j; i++)
142 if (docRoots[i]==root || (docRoots[i]!=null && docRoots[i].getId().equals(r_id)))
147 * verify that newr version is really an intact version of the
148 * @param newVersion (may be modified)
150 * @return true if newVersion is a valid root that preserves original references
152 private boolean isValidUpdate(VAMSAS newVersion, final VAMSAS oldVersion) {
153 // ideal - this cascades down the two structures, ensuring that all ID'd objects in one are present in the other.
154 if (oldVersion==newVersion) {
155 // may be a virgin root element.
156 if (!newVersion.isRegistered())
157 _registerObject(newVersion);
158 // Should retrieve original version and compare - unless local hashes can be used to determine if resultSet has been truncated.
159 // just do internal validation for moment.
160 if (newVersion.isValid())
164 // redundant ? if (oldVersion.is__stored_in_document())
165 if (!newVersion.isRegistered())
166 _registerObject(newVersion);
167 if (newVersion.isValid())
172 * LATER isValidUpdate : Ideally. we efficiently walk down, comparing hashes, to deal with merging and verifying provenance for objects
174 // extract root objects
175 if (newroots != null) {
176 // check newroots for objects that were present in the old document
177 // check to see if the 'old' objects have been modified
178 // if they have ? we overwrite them with their new version, ensuring that
179 // provenance is updated.
180 // if they haven't ? do nothing ?
182 for (int i = 0, k = newroots.length; i < k; i++) {
183 if (newroots[i].isRegistered()) {
184 // easy - just check if anything has changed and do provenance
185 Vobject oldversion = getObject(newroots[i].getVorbaId());
186 if (oldversion instanceof VAMSAS) {
187 // LATER: appropriate merging behaviour when two clients have improperly modified the same Vobject independently.
188 if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
189 // client has modified this Vobject since last retrieval.
190 if (newroots[i].get__last_hash() != oldversion.get__last_hash()) {
191 // Vobject has been modified by another client since this
193 // last access to document.
198 "SimpleClient error when using setVamsasRoots : The vorbaId for Vobject "
200 + " does not refer to an Vobject of type VAMSAS in the current document!");
203 if (!newroots[i].is__stored_in_document()) {
204 // check if Vobject is modified
205 if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
206 // it is - so we add newroots[i] as a new Vobject, with updated
213 // just add newroots[i] as a new Vobject in the document
214 // - with appropriate provenance.
220 * merge old and new root vectors
221 * @param newr This array may be written to
223 * @param the client document (usually this) which this root set belongs to.
224 * @return merged vector of vamsas roots
226 private VAMSAS[] _combineRoots(VAMSAS[] newr, final VAMSAS[] original, ClientDocument modflag) {
227 Vector rts = new Vector();
228 boolean modified=false;
229 for (int i=0,j=original.length; i<j; i++) {
230 int k = _contains(original[i], newr);
232 if (isValidUpdate(newr[k], original[i])) {
237 // LATER: try harder to merge ducument roots.
238 log.warn("Couldn't merge new VAMSAS root "+newr[k].getId());
239 newr[k] = null; // LATER: this means we ignore mangled roots. NOT GOOD
243 rts.add(original[i]);
246 // add remaining (new) roots
247 for (int i=0,j=newr.length; i<j; i++) {
253 newr = new VAMSAS[rts.size()];
254 for (int i=0,j=rts.size(); i<j; i++)
255 newr[i] = (VAMSAS) rts.get(i);
257 modflag.isModified = modified;
262 * update the document with new roots.
263 * LATER: decide: this affects the next call to getVamsasRoots()
264 * @see org.vamsas.IClientDocument.setVamsasRoots
266 public void setVamsasRoots(VAMSAS[] newroots) {
268 log.debug("setVamsasRoots called on null document.");
272 if (newroots==null) {
273 log.debug("setVamsasRoots(null) - do nothing.");
276 // are we dealing with same array ?
277 if (_VamsasRoots!=newroots) {
278 // merge roots into local version.
279 newr = new VAMSAS[newroots.length];
280 for (int i=0;i<newr.length;i++)
281 newr[i] = newroots[i];
282 newr=_combineRoots(newr,_VamsasRoots,this);
284 newr = new VAMSAS[_VamsasRoots.length];
285 for (int i=0;i<newr.length;i++)
286 newr[i]=_VamsasRoots[i];
288 // actually compare with document root set for final combination (to ensure nothing is lost)
289 _VamsasRoots = _combineRoots(newr, doc.getVAMSAS(), this);
294 * LATER: decide: this affects the next call to getVamsasRoots()
295 * @see org.vamsas.client.IClientDocument#addVamsasRoot(org.vamsas.objects.core.VAMSAS)
297 public void addVamsasRoot(VAMSAS newroot) {
299 log.debug("addVamsasRoots called on null document.");
302 VAMSAS[] newroots = _combineRoots(new VAMSAS[] {newroot}, _VamsasRoots, this);
303 _VamsasRoots = newroots;
309 * @see org.vamsas.client.IClientDocument#registerObjects(org.vamsas.client.Vobject[])
311 public VorbaId[] registerObjects(Vobject[] unregistered) {
313 log.warn("registerObjects[] called on null document.");
316 if (vamsasObjects==null) {
317 log.warn("registerObjects[] called for null vamsasObjects hasharray.");
320 if (unregistered!=null) {
321 VorbaId ids[] = new VorbaId[unregistered.length];
322 for (int i=0,k=unregistered.length; i<k; i++)
323 if (unregistered[i]!=null) {
324 log.warn("Null Vobject passed to registerObject[] at position "+i);
327 ids[i]=registerObject(unregistered[i]);
329 log.debug("Registered "+unregistered.length+" objects - total of "+vamsasObjects.size()+" ids.");
335 * @see org.vamsas.client.IClientDocument#registerObject(org.vamsas.client.Vobject)
337 public VorbaId registerObject(Vobject unregistered) {
339 log.warn("registerObjects called on null document.");
342 if (vamsasObjects==null) {
343 log.warn("registerObjects called for null vamsasObjects hasharray.");
346 if (unregistered!=null) {
347 VorbaId id = _registerObject(unregistered);
348 log.debug("Registered object - total of "+vamsasObjects.size()+" ids.");
351 log.warn("Null Vobject passed to registerObject.");
355 * IClientAppdata instance - if it exists.
357 SimpleClientAppdata scappd = null;
359 * @see org.vamsas.client.IClientDocument#getClientAppdata()
361 public IClientAppdata getClientAppdata() {
363 log.warn("getClientAppdata called on null document.");
367 log.debug("Creating new SimpleClientAppdata instance for "+sclient.getSessionHandle());
368 scappd = new SimpleClientAppdata(this);
370 // LATER: may not need this as a warning message.
371 log.warn("Null appdata object for "+sclient.getSessionHandle());
373 log.debug("Created SimpleClientAppdata successfully.");
376 log.debug("Returning existing SimpleClientAppdata reference.");
381 * access the vamsas document
382 * @return the session's vamsas document
384 protected VamsasDocument getVamsasDocument() {
388 * returns the read-only IO interface for the vamsas document Jar file
391 protected VamsasArchiveReader getVamsasArchiveReader() {
393 return archive.getOriginalArchiveReader();
394 } catch (Exception e) {
395 log.warn("Unable to create OriginalArchiveReader!", e);
399 protected boolean updateSessionDocument() throws java.io.IOException {
400 boolean docupdate = true; // 'non-serious' problems below set this false
402 log.warn("updateSessionDocument called on null document.");
403 throw new java.io.IOException("Document is closed.");
406 log.warn("updateSessionDocument called document archive handler.");
407 throw new java.io.IOException("Document is closed.");
410 if (!isModified() && !scappd.isModified()) {
411 log.debug("Document update not necessary. returning false.");
414 VamsasSession session = sclient._session;
415 log.debug("updating Session Document in "+session.sessionDir);
416 // update the VamsasDocument structure with any new appData's.
417 // try to update the sessionFile
418 log.debug("Attempting to update session "+sclient.session.getSessionUrn());
419 if (scappd.isModified()) {
420 ClientHandle client = sclient.client;
421 UserHandle user = sclient.user;
422 scappd.closeForWriting();
423 if (scappd.appsGlobal==null) {
424 log.debug("Creating new appData entry for this application...");
425 // first write for this application - add a new section in document
426 ApplicationData appd = scappd.appsGlobal = new ApplicationData();
427 appd.setName(client.getClientName());
428 // appd.setUrn(client.getClientUrn());
429 appd.setVersion(client.getVersion());
430 doc.addApplicationData(appd);
431 // embed or jarEntry ? - for now only jarEntry's are dealt with.
432 appd.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()));
433 log.debug("... created.");
435 if (scappd.newAppData!=null && scappd.newAppData.sessionFile.exists()) {
436 log.debug("Beginning update for new Global Appdata...");
437 // new global appdata to write.
438 if (scappd.appsGlobal.getData()!=null) {
439 scappd.appsGlobal.setData(null);
440 scappd.appsGlobal.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()));
442 // LATER: use a switch to decide if the data should be written as a reference or as an embedded data chunk
443 scappd.updateAnAppdataEntry(archive, scappd.appsGlobal, scappd.newAppData);
444 log.debug("...Successfully updated Global Appdata Entry.");
446 if (scappd.newUserData!=null && scappd.newUserData.sessionFile.exists()) {
447 log.debug("Beginning to update Users Appdata entry....");
448 if (scappd.usersData==null) {
449 // create new user appdata
450 scappd.usersData = new User();
451 scappd.usersData.setFullname(user.getFullName());
452 scappd.usersData.setOrganization(user.getOrganization());
453 scappd.appsGlobal.addUser(scappd.usersData);
455 User appd = scappd.usersData;
456 if (appd.getData()!=null || appd.getDataReference()==null) {
457 // LATER make standard appDataReference constructor for client+user
459 String safe_username = user.getFullName();
460 int t = safe_username.indexOf(" ");
462 safe_username = safe_username.substring(t);
464 appd.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()+safe_username));
466 scappd.updateAnAppdataEntry(archive, scappd.usersData, scappd.newUserData);
467 log.debug("...Successfully updated user AppData entry.");
470 log.debug("Updating Document...");
471 // now update the document.
473 archive.putVamsasDocument(doc);
474 log.debug("Successfully written document entry.");
476 catch (Exception e) {
477 log.error("Marshalling error for vamsas document.",e);
478 docupdate = false; // pass on the (probable) object validation error
480 if (archive.transferRemainingAppDatas())
481 log.debug("Remaining appdatas were transferred.");
483 log.debug("No remaining appdatas were transferred. (Correct?)");
484 archive.closeArchive();
485 log.debug("...successully finished and closed.");
486 return docupdate; // no errors ?
489 * @see java.lang.Object#finalize()
491 protected void finalize() throws Throwable {
492 log.debug("Garbage collecting on ClientDocument instance.");
500 // disengage from client
502 sclient.cdocument = null;
507 public Vector getUpdatedObjects() {
508 return updatedObjects;