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) {
71 if (objrefs.containsKey(id))
72 return (Vobject) objrefs.get(id);
73 log.debug("Returning null Vobject reference for id "+id.getId());
80 * @see org.vamsas.client.IClientDocument#getObjects(org.vamsas.client.VorbaId[])
82 public Vobject[] getObjects(VorbaId[] ids) {
83 Vobject[] vo = new Vobject[ids.length];
84 for (int i=0,j=ids.length; i<j;i++)
85 if (objrefs.containsKey(ids[i]))
86 vo[i] = (Vobject) objrefs.get(ids[i]);
88 log.debug("Returning null Vobject reference for id "+ids[i].getId());
92 * internal reference to single copy of Document Roots array
94 private VAMSAS[] _VamsasRoots=null;
97 * 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)
98 * @see org.vamsas.client.IClientDocument#getVamsasRoots()
100 public VAMSAS[] getVamsasRoots() {
101 if (_VamsasRoots!=null)
103 VAMSAS[] roots = doc.getVAMSAS();
105 // Make a new one to return to client : TODO: Decide if this is correct
106 _VamsasRoots = new VAMSAS[] { new VAMSAS() };
108 _VamsasRoots = new VAMSAS[roots.length];
109 for (int r=0;r<roots.length; r++)
110 _VamsasRoots[r] = roots[r];
115 private int _contains(VAMSAS root, VAMSAS[] docRoots) {
118 if (docRoots==null || docRoots.length==0)
120 String r_id = root.getId();
121 for (int i=0,j=docRoots.length; i<j; i++)
122 if (docRoots[i]==root || (docRoots[i]!=null && docRoots[i].getId().equals(r_id)))
127 * verify that newr version is really an intact version of the
128 * @param newVersion (may be modified)
130 * @return true if newVersion is a valid root that preserves original references
132 private boolean isValidUpdate(VAMSAS newVersion, final VAMSAS oldVersion) {
133 // ideal - this cascades down the two structures, ensuring that all ID'd objects in one are present in the other.
134 if (oldVersion==newVersion) {
135 // may be a virgin root element.
136 if (!newVersion.isRegistered())
137 _registerObject(newVersion);
138 // Should retrieve original version and compare - unless local hashes can be used to determine if resultSet has been truncated.
139 // just do internal validation for moment.
140 if (newVersion.isValid())
144 // redundant ? if (oldVersion.is__stored_in_document())
145 if (!newVersion.isRegistered())
146 _registerObject(newVersion);
147 if (newVersion.isValid())
152 * LATER isValidUpdate : Ideally. we efficiently walk down, comparing hashes, to deal with merging and verifying provenance for objects
154 // extract root objects
155 if (newroots != null) {
156 // check newroots for objects that were present in the old document
157 // check to see if the 'old' objects have been modified
158 // if they have ? we overwrite them with their new version, ensuring that
159 // provenance is updated.
160 // if they haven't ? do nothing ?
162 for (int i = 0, k = newroots.length; i < k; i++) {
163 if (newroots[i].isRegistered()) {
164 // easy - just check if anything has changed and do provenance
165 Vobject oldversion = getObject(newroots[i].getVorbaId());
166 if (oldversion instanceof VAMSAS) {
167 // LATER: appropriate merging behaviour when two clients have improperly modified the same Vobject independently.
168 if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
169 // client has modified this Vobject since last retrieval.
170 if (newroots[i].get__last_hash() != oldversion.get__last_hash()) {
171 // Vobject has been modified by another client since this
173 // last access to document.
178 "SimpleClient error when using setVamsasRoots : The vorbaId for Vobject "
180 + " does not refer to an Vobject of type VAMSAS in the current document!");
183 if (!newroots[i].is__stored_in_document()) {
184 // check if Vobject is modified
185 if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
186 // it is - so we add newroots[i] as a new Vobject, with updated
193 // just add newroots[i] as a new Vobject in the document
194 // - with appropriate provenance.
200 * merge old and new root vectors
201 * @param newr This array may be written to
203 * @param the client document (usually this) which this root set belongs to.
204 * @return merged vector of vamsas roots
206 private VAMSAS[] _combineRoots(VAMSAS[] newr, final VAMSAS[] original, ClientDocument modflag) {
207 Vector rts = new Vector();
208 boolean modified=false;
209 for (int i=0,j=original.length; i<j; i++) {
210 int k = _contains(original[i], newr);
212 if (isValidUpdate(newr[k], original[i])) {
217 // LATER: try harder to merge ducument roots.
218 log.warn("Couldn't merge new VAMSAS root "+newr[k].getId());
219 newr[k] = null; // LATER: this means we ignore mangled roots. NOT GOOD
223 rts.add(original[i]);
226 // add remaining (new) roots
227 for (int i=0,j=newr.length; i<j; i++) {
233 newr = new VAMSAS[rts.size()];
234 for (int i=0,j=rts.size(); i<j; i++)
235 newr[i] = (VAMSAS) rts.get(i);
237 modflag.isModified = modified;
242 * update the document with new roots.
243 * LATER: decide: this affects the next call to getVamsasRoots()
244 * @see org.vamsas.IClientDocument.setVamsasRoots
246 public void setVamsasRoots(VAMSAS[] newroots) {
248 if (newroots==null) {
249 log.debug("setVamsasRoots(null) - do nothing.");
252 // are we dealing with same array ?
253 if (_VamsasRoots!=newroots) {
254 // merge roots into local version.
255 newr = new VAMSAS[newroots.length];
256 for (int i=0;i<newr.length;i++)
257 newr[i] = newroots[i];
258 newr=_combineRoots(newr,_VamsasRoots,this);
260 newr = new VAMSAS[_VamsasRoots.length];
261 for (int i=0;i<newr.length;i++)
262 newr[i]=_VamsasRoots[i];
264 // actually compare with document root set for final combination (to ensure nothing is lost)
265 _VamsasRoots = _combineRoots(newr, doc.getVAMSAS(), this);
270 * LATER: decide: this affects the next call to getVamsasRoots()
271 * @see org.vamsas.client.IClientDocument#addVamsasRoot(org.vamsas.objects.core.VAMSAS)
273 public void addVamsasRoot(VAMSAS newroot) {
274 VAMSAS[] newroots = _combineRoots(new VAMSAS[] {newroot}, _VamsasRoots, this);
275 _VamsasRoots = newroots;
281 * @see org.vamsas.client.IClientDocument#registerObjects(org.vamsas.client.Vobject[])
283 public VorbaId[] registerObjects(Vobject[] unregistered) {
284 if (unregistered!=null) {
285 VorbaId ids[] = new VorbaId[unregistered.length];
286 for (int i=0,k=unregistered.length; i<k; i++)
287 if (unregistered[i]!=null) {
288 log.warn("Null Vobject passed to registerObject[] at position "+i);
291 ids[i]=registerObject(unregistered[i]);
293 log.debug("Registered "+unregistered.length+" objects - total of "+objrefs.size()+" ids.");
299 * @see org.vamsas.client.IClientDocument#registerObject(org.vamsas.client.Vobject)
301 public VorbaId registerObject(Vobject unregistered) {
302 if (unregistered!=null) {
303 VorbaId id = _registerObject(unregistered);
304 log.debug("Registered object - total of "+objrefs.size()+" ids.");
307 log.warn("Null Vobject passed to registerObject.");
311 * IClientAppdata instance - if it exists.
313 SimpleClientAppdata scappd = null;
315 * @see org.vamsas.client.IClientDocument#getClientAppdata()
317 public IClientAppdata getClientAppdata() {
319 log.debug("Creating new SimpleClientAppdata instance for "+sclient.getSessionHandle());
320 scappd = new SimpleClientAppdata(this);
322 // LATER: may not need this as a warning message.
323 log.warn("Null appdata object for "+sclient.getSessionHandle());
325 log.debug("Created SimpleClientAppdata successfully.");
328 log.debug("Returning existing SimpleClientAppdata reference.");
333 * access the vamsas document
334 * @return the session's vamsas document
336 protected VamsasDocument getVamsasDocument() {
340 * returns the read-only IO interface for the vamsas document Jar file
343 protected VamsasArchiveReader getVamsasArchiveReader() {
345 return archive.getOriginalArchiveReader();
346 } catch (Exception e) {
347 log.warn("Unable to create OriginalArchiveReader!", e);
351 protected boolean updateSessionDocument() throws java.io.IOException {
352 boolean docupdate = true; // 'non-serious' problems below set this false
353 if (!isModified() && !scappd.isModified()) {
354 log.debug("Document update not necessary. returning false.");
357 VamsasSession session = sclient._session;
358 log.debug("updating Session Document in "+session.sessionDir);
359 // update the VamsasDocument structure with any new appData's.
360 // try to update the sessionFile
361 log.debug("Attempting to update session "+sclient.session.getSessionUrn());
362 if (scappd.isModified()) {
363 ClientHandle client = sclient.client;
364 UserHandle user = sclient.user;
365 scappd.closeForWriting();
366 if (scappd.appsGlobal==null) {
367 log.debug("Creating new appData entry for this application...");
368 // first write for this application - add a new section in document
369 ApplicationData appd = scappd.appsGlobal = new ApplicationData();
370 appd.setName(client.getClientName());
371 appd.setUrn(client.getClientUrn());
372 appd.setVersion(client.getVersion());
373 doc.addApplicationData(appd);
374 // embed or jarEntry ? - for now only jarEntry's are dealt with.
375 appd.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()));
376 log.debug("... created.");
378 if (scappd.newAppData!=null && scappd.newAppData.sessionFile.exists()) {
379 log.debug("Beginning update for new Global Appdata...");
380 // new global appdata to write.
381 if (scappd.appsGlobal.getData()!=null) {
382 scappd.appsGlobal.setData(null);
383 scappd.appsGlobal.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()));
385 // LATER: use a switch to decide if the data should be written as a reference or as an embedded data chunk
386 scappd.updateAnAppdataEntry(archive, scappd.appsGlobal, scappd.newAppData);
387 log.debug("...Successfully updated Global Appdata Entry.");
389 if (scappd.newUserData!=null && scappd.newUserData.sessionFile.exists()) {
390 log.debug("Beginning to update Users Appdata entry....");
391 if (scappd.usersData==null) {
392 // create new user appdata
393 scappd.usersData = new User();
394 scappd.usersData.setFullname(user.getFullName());
395 scappd.usersData.setOrganization(user.getOrganization());
396 scappd.appsGlobal.addUser(scappd.usersData);
398 User appd = scappd.usersData;
399 if (appd.getData()!=null || appd.getDataReference()==null) {
400 // LATER make standard appDataReference constructor for client+user
402 String safe_username = user.getFullName();
403 int t = safe_username.indexOf(" ");
405 safe_username = safe_username.substring(t);
407 appd.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()+safe_username));
409 scappd.updateAnAppdataEntry(archive, scappd.usersData, scappd.newUserData);
410 log.debug("...Successfully updated user AppData entry.");
413 log.debug("Updating Document...");
414 // now update the document.
416 archive.putVamsasDocument(doc);
417 log.debug("Successfully written document entry.");
419 catch (Exception e) {
420 log.error("Marshalling error for vamsas document.",e);
421 docupdate = false; // pass on the (probable) object validation error
423 if (archive.transferRemainingAppDatas())
424 log.debug("Remaining appdatas were transferred.");
426 log.debug("No remaining appdatas were transferred. (Correct?)");
427 archive.closeArchive();
428 log.debug("...successully finished and closed.");
430 return docupdate; // no errors ?
433 * @see java.lang.Object#finalize()
435 protected void finalize() throws Throwable {
436 log.debug("Garbage collecting on ClientDocument instance.");
441 // TODO local garbage collection