refactored org to uk
[vamsas.git] / src / org / vamsas / client / simpleclient / ClientDocument.java
index 71365ee..3b654f8 100644 (file)
@@ -3,22 +3,23 @@
  */
 package org.vamsas.client.simpleclient;
 
-import java.util.Hashtable;
+import java.io.IOException;
 import java.util.Vector;
 
 import org.apache.commons.logging.Log;
 import org.apache.commons.logging.LogFactory;
-import org.vamsas.client.IClient;
+import org.vamsas.client.ClientHandle;
 import org.vamsas.client.IClientAppdata;
 import org.vamsas.client.IClientDocument;
-import org.vamsas.client.VorbaId;
+import org.vamsas.client.UserHandle;
 import org.vamsas.client.Vobject;
-import org.vamsas.objects.core.AppData;
+import org.vamsas.client.VorbaId;
 import org.vamsas.objects.core.ApplicationData;
 import org.vamsas.objects.core.User;
 import org.vamsas.objects.core.VAMSAS;
 import org.vamsas.objects.core.VamsasDocument;
 import org.vamsas.objects.utils.AppDataReference;
+import org.vamsas.test.objects.Core;
 
 /**
  * Maintains a collection of vamsas objects, appdatas and states, and provides api for a SimpleClient's client.
@@ -40,6 +41,7 @@ public class ClientDocument extends org.vamsas.client.ClientDocument implements
   public boolean isModified() {
     return isModified;
   }
+  private Vector updatedObjects=null;
   /**
    *
    *  prepare Application-side dataset from the vamsas Document archive
@@ -51,12 +53,14 @@ public class ClientDocument extends org.vamsas.client.ClientDocument implements
   protected ClientDocument(VamsasDocument doc, VamsasArchive docHandler, IdFactory Factory, SimpleClient sclient) {
     super(Factory.getVorbaIdHash(), Factory);
     
+    
     /**
      * prepare Application-side dataset from the vamsas Document archive
      */
     this.sclient = sclient;
     archive = docHandler;
     this.doc = doc;
+    updatedObjects=null;  /// TODO: correct this line
   }
   
   /*
@@ -65,8 +69,13 @@ public class ClientDocument extends org.vamsas.client.ClientDocument implements
    * @see org.vamsas.client.IClientDocument#getObject(org.vamsas.client.VorbaId)
    */
   public Vobject getObject(VorbaId id) {
-    // TODO: look up id in document Vobject
-    // retrieve Vobject and return
+    if (vamsasObjects==null) {
+      log.debug("getObject called on null objrefs list.");
+      return null;
+    }
+    if (vamsasObjects.containsKey(id))
+      return (Vobject) vamsasObjects.get(id);
+    log.debug("Returning null Vobject reference for id "+id.getId());
     return null;
   }
   
@@ -76,8 +85,17 @@ public class ClientDocument extends org.vamsas.client.ClientDocument implements
    * @see org.vamsas.client.IClientDocument#getObjects(org.vamsas.client.VorbaId[])
    */
   public Vobject[] getObjects(VorbaId[] ids) {
-    // TODO: getObject in bulk
-    return null;
+    if (vamsasObjects==null) {
+      log.debug("getObject[]  called on null vamsasObjects list.");
+      return null;
+    }
+    Vobject[] vo = new Vobject[ids.length];
+    for (int i=0,j=ids.length; i<j;i++) 
+      if (vamsasObjects.containsKey(ids[i]))
+        vo[i] = (Vobject) vamsasObjects.get(ids[i]);
+      else
+        log.debug("Returning null Vobject reference for id "+ids[i].getId());
+    return vo;
   }
   /**
    * internal reference to single copy of Document Roots array
@@ -89,12 +107,23 @@ public class ClientDocument extends org.vamsas.client.ClientDocument implements
    * @see org.vamsas.client.IClientDocument#getVamsasRoots()
    */
   public VAMSAS[] getVamsasRoots() {
+    if (doc==null) {
+      log.debug("Null document for getVamsasRoots(), returning null");
+      return null;
+    }
+    if (archive==null) {
+      // LATER: decide on read-only status of ClientDocument object
+      log.warn("getVamsasRoots() called on possibly read-only document.");
+    }
     if (_VamsasRoots!=null)
       return _VamsasRoots;
     VAMSAS[] roots = doc.getVAMSAS();
     if (roots == null) {
-      // Make a new one to return to client : TODO: Decide if this is correct
+      // Make a new one to return to client to get filled. 
       _VamsasRoots = new VAMSAS[] { new VAMSAS() };
+      // Do provenance now. just in case.
+      doc.getProvenance().addEntry(sclient.getProvenanceEntry("Created new document root [id="+_VamsasRoots[0].getId()+"]"));
+      doc.addVAMSAS(_VamsasRoots[0]);
     } else {
       _VamsasRoots = new VAMSAS[roots.length];
       for (int r=0;r<roots.length; r++)
@@ -121,7 +150,6 @@ public class ClientDocument extends org.vamsas.client.ClientDocument implements
  * @return true if newVersion is a valid root that preserves original references
  */
   private boolean isValidUpdate(VAMSAS newVersion, final VAMSAS oldVersion) {
-    // LATER: IMPLEMENT
     // ideal - this cascades down the two structures, ensuring that all ID'd objects in one are present in the other.
     if (oldVersion==newVersion) {
       // may be a virgin root element.
@@ -140,6 +168,53 @@ public class ClientDocument extends org.vamsas.client.ClientDocument implements
         return true;
     }
     return false;
+    /**
+     * LATER isValidUpdate : Ideally. we efficiently walk down, comparing hashes, to deal with merging and verifying provenance for objects
+    
+    // extract root objects
+    if (newroots != null) {
+      // check newroots for objects that were present in the old document
+      // check to see if the 'old' objects have been modified
+      // if they have ? we overwrite them with their new version, ensuring that
+      // provenance is updated.
+      // if they haven't ? do nothing ?
+      
+      for (int i = 0, k = newroots.length; i < k; i++) {
+        if (newroots[i].isRegistered()) {
+          // easy - just check if anything has changed and do provenance
+          Vobject oldversion = getObject(newroots[i].getVorbaId());
+          if (oldversion instanceof VAMSAS) {
+            // LATER: appropriate merging behaviour when two clients have improperly modified the same Vobject independently.
+            if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
+              // client has modified this Vobject since last retrieval.
+              if (newroots[i].get__last_hash() != oldversion.get__last_hash()) {
+                // Vobject has been modified by another client since this
+                // client's
+                // last access to document.
+              }
+            }
+          } else {
+            throw new Error(
+                "SimpleClient error when using setVamsasRoots : The vorbaId for Vobject "
+                + i
+                + " does not refer to an Vobject of type VAMSAS in the current document!");
+          }
+        } else {
+          if (!newroots[i].is__stored_in_document()) {
+            // check if Vobject is modified
+            if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
+              // it is - so we add newroots[i] as a new Vobject, with updated
+              // provenance.
+            } else {
+              // do nothing
+              newroots[i] = null;
+            }
+          } else {
+            // just add newroots[i] as a new Vobject in the document
+            // - with appropriate provenance.
+          }
+        }
+      }*/
   }
   /**
    * merge old and new root vectors
@@ -186,65 +261,44 @@ public class ClientDocument extends org.vamsas.client.ClientDocument implements
   /**
    * update the document with new roots.
    * LATER: decide: this affects the next call to getVamsasRoots()
+   * @see org.vamsas.IClientDocument.setVamsasRoots
    */
   public void setVamsasRoots(VAMSAS[] newroots) {
-    
+    if (doc==null) {
+      log.debug("setVamsasRoots called on null document.");
+      return;
+    }
+    VAMSAS[] newr;
+    if (newroots==null) {
+      log.debug("setVamsasRoots(null) - do nothing.");
+      return;
+    }
     // are we dealing with same array ?
     if (_VamsasRoots!=newroots) {
-      // merge roots into 
-    }
-    // extract root objects
-    if (newroots != null) {
-      // check newroots for objects that were present in the old document
-      // check to see if the 'old' objects have been modified
-      // if they have ? we overwrite them with their new version, ensuring that
-      // provenance is updated.
-      // if they haven't ? do nothing ?
-      
-      for (int i = 0, k = newroots.length; i < k; i++) {
-        if (newroots[i].isRegistered()) {
-          // easy - just check if anything has changed and do provenance
-          Vobject oldversion = getObject(newroots[i].getVorbaId());
-          if (oldversion instanceof VAMSAS) {
-            // LATER: appropriate merging behaviour when two clients have improperly modified the same Vobject independently.
-            if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
-              // client has modified this Vobject since last retrieval.
-              if (newroots[i].get__last_hash() != oldversion.get__last_hash()) {
-                // Vobject has been modified by another client since this
-                // client's
-                // last access to document.
-              }
-            }
-          } else {
-            throw new Error(
-                "SimpleClient error when using setVamsasRoots : The vorbaId for Vobject "
-                + i
-                + " does not refer to an Vobject of type VAMSAS in the current document!");
-          }
-        } else {
-          if (!newroots[i].is__stored_in_document()) {
-            // check if Vobject is modified
-            if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
-              // it is - so we add newroots[i] as a new Vobject, with updated
-              // provenance.
-            } else {
-              // do nothing
-              newroots[i] = null;
-            }
-          } else {
-            // just add newroots[i] as a new Vobject in the document
-            // - with appropriate provenance.
-          }
-        }
-      }
+      // merge roots into local version.
+      newr = new VAMSAS[newroots.length];
+      for (int i=0;i<newr.length;i++)
+        newr[i] = newroots[i];
+      newr=_combineRoots(newr,_VamsasRoots,this);
+    } else {
+      newr = new VAMSAS[_VamsasRoots.length];
+      for (int i=0;i<newr.length;i++)
+        newr[i]=_VamsasRoots[i];
     }
+    //  actually compare with document root set for final combination (to ensure nothing is lost)
+    _VamsasRoots = _combineRoots(newr, doc.getVAMSAS(), this); 
   }
   
+  
   /* (non-Javadoc)
    * LATER: decide: this affects the next call to getVamsasRoots()
    * @see org.vamsas.client.IClientDocument#addVamsasRoot(org.vamsas.objects.core.VAMSAS)
    */
   public void addVamsasRoot(VAMSAS newroot) {
+    if (doc==null) {
+      log.debug("addVamsasRoots called on null document.");
+      return;
+    }
     VAMSAS[] newroots = _combineRoots(new VAMSAS[] {newroot}, _VamsasRoots, this);
     _VamsasRoots = newroots;  
   }
@@ -255,6 +309,14 @@ public class ClientDocument extends org.vamsas.client.ClientDocument implements
    * @see org.vamsas.client.IClientDocument#registerObjects(org.vamsas.client.Vobject[])
    */
   public VorbaId[] registerObjects(Vobject[] unregistered) {
+    if (doc==null) {
+      log.warn("registerObjects[] called on null document.");
+      return null;
+    }
+    if (vamsasObjects==null) {
+      log.warn("registerObjects[] called for null vamsasObjects hasharray.");
+      return null;
+    }
     if (unregistered!=null) {
       VorbaId ids[] = new VorbaId[unregistered.length];
       for (int i=0,k=unregistered.length; i<k; i++)
@@ -264,6 +326,7 @@ public class ClientDocument extends org.vamsas.client.ClientDocument implements
         } else {
           ids[i]=registerObject(unregistered[i]);
         }
+      log.debug("Registered "+unregistered.length+" objects - total of "+vamsasObjects.size()+" ids.");
       return ids;
     }
     return null;
@@ -272,8 +335,19 @@ public class ClientDocument extends org.vamsas.client.ClientDocument implements
    * @see org.vamsas.client.IClientDocument#registerObject(org.vamsas.client.Vobject)
    */
   public VorbaId registerObject(Vobject unregistered) {
-    if (unregistered!=null)
-      return _registerObject(unregistered);
+    if (doc==null) {
+      log.warn("registerObjects called on null document.");
+      return null;
+    }
+    if (vamsasObjects==null) {
+      log.warn("registerObjects called for null vamsasObjects hasharray.");
+      return null;
+    }
+    if (unregistered!=null) {
+      VorbaId id = _registerObject(unregistered);
+      log.debug("Registered object - total of "+vamsasObjects.size()+" ids.");
+      return id;
+    }
     log.warn("Null Vobject passed to registerObject.");
     return null;
   }
@@ -285,6 +359,10 @@ public class ClientDocument extends org.vamsas.client.ClientDocument implements
    * @see org.vamsas.client.IClientDocument#getClientAppdata()
    */
   public IClientAppdata getClientAppdata() {
+    if (doc==null) {
+      log.warn("getClientAppdata called on null document.");
+      return null;
+    }
     if (scappd==null) {
       log.debug("Creating new SimpleClientAppdata instance for "+sclient.getSessionHandle());
       scappd = new SimpleClientAppdata(this);
@@ -299,18 +377,6 @@ public class ClientDocument extends org.vamsas.client.ClientDocument implements
     }
     return scappd;
   }
-  /* (non-Javadoc)
-   * @see java.lang.Object#finalize()
-   */
-  protected void finalize() throws Throwable {
-    log.debug("Garbage collecting on ClientDocument instance.");
-    if (scappd!=null) {
-      scappd.finalize();
-      scappd = null;
-    }
-    
-    super.finalize();
-  }
   /**
    * access the vamsas document
    * @return the session's vamsas document
@@ -330,4 +396,115 @@ public class ClientDocument extends org.vamsas.client.ClientDocument implements
     }
     return null;
   }
+  protected boolean updateSessionDocument() throws java.io.IOException {
+    boolean docupdate = true; // 'non-serious' problems below set this false
+    if (doc==null) {
+      log.warn("updateSessionDocument called on null document.");
+      throw new java.io.IOException("Document is closed.");
+    }
+    if (archive==null) {
+      log.warn("updateSessionDocument called document archive handler.");
+      throw new java.io.IOException("Document is closed.");
+    }
+    
+    if (!isModified() && !scappd.isModified()) {
+      log.debug("Document update not necessary. returning false.");
+      return false;
+    }
+    VamsasSession session = sclient._session;
+    log.debug("updating Session Document in "+session.sessionDir);
+    // update the VamsasDocument structure with any new appData's.
+    // try to update the sessionFile
+    log.debug("Attempting to update session "+sclient.session.getSessionUrn());
+    if (scappd.isModified()) {
+      ClientHandle client = sclient.client;
+      UserHandle user = sclient.user;
+      scappd.closeForWriting();      
+      if (scappd.appsGlobal==null) {
+        log.debug("Creating new appData entry for this application...");
+        // first write for this application - add a new section in document
+        ApplicationData appd = scappd.appsGlobal = new ApplicationData();
+        appd.setName(client.getClientName());
+        // appd.setUrn(client.getClientUrn());
+        appd.setVersion(client.getVersion());
+        doc.addApplicationData(appd);
+        // embed or jarEntry ?  - for now only jarEntry's are dealt with.
+        appd.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()));
+        log.debug("... created.");
+      }
+      if (scappd.newAppData!=null && scappd.newAppData.sessionFile.exists()) {
+        log.debug("Beginning update for new Global Appdata...");
+        // new global appdata to write.
+        if (scappd.appsGlobal.getData()!=null) {
+          scappd.appsGlobal.setData(null);
+          scappd.appsGlobal.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()));
+        }
+        // LATER: use a switch to decide if the data should be written as a reference or as an embedded data chunk
+        scappd.updateAnAppdataEntry(archive, scappd.appsGlobal, scappd.newAppData);
+        log.debug("...Successfully updated Global Appdata Entry.");
+      }
+      if (scappd.newUserData!=null && scappd.newUserData.sessionFile.exists()) {
+        log.debug("Beginning to update Users Appdata entry....");
+        if (scappd.usersData==null) {
+          // create new user appdata
+          scappd.usersData = new User();
+          scappd.usersData.setFullname(user.getFullName());
+          scappd.usersData.setOrganization(user.getOrganization());
+          scappd.appsGlobal.addUser(scappd.usersData);
+        }
+        User appd = scappd.usersData;
+        if (appd.getData()!=null || appd.getDataReference()==null) {
+          // LATER make standard appDataReference constructor for client+user 
+          appd.setData(null);          
+          String safe_username = user.getFullName();
+          int t = safe_username.indexOf(" ");
+          if (t!=-1) {
+            safe_username = safe_username.substring(t);
+          }
+          appd.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()+safe_username));
+        }
+        scappd.updateAnAppdataEntry(archive, scappd.usersData, scappd.newUserData);
+        log.debug("...Successfully updated user AppData entry.");
+      }
+    }
+    log.debug("Updating Document...");
+    // now update the document.
+    try {
+      archive.putVamsasDocument(doc);
+      log.debug("Successfully written document entry.");
+    }
+    catch (Exception e) {
+      log.error("Marshalling error for vamsas document.",e);
+      docupdate = false; // pass on the (probable) object validation error 
+    }
+    if (archive.transferRemainingAppDatas())
+      log.debug("Remaining appdatas were transferred.");
+    else
+      log.debug("No remaining appdatas were transferred. (Correct?)");
+    archive.closeArchive();
+    log.debug("...successully finished and closed.");
+    return docupdate; // no errors ?
+  }
+  /* (non-Javadoc)
+   * @see java.lang.Object#finalize()
+   */
+  protected void finalize() throws Throwable {
+    log.debug("Garbage collecting on ClientDocument instance.");
+    if (scappd!=null) {
+      scappd.finalize();
+      scappd = null;
+    }
+    if (doc!=null) {
+      doc = null;
+    }
+    // disengage from client
+    if (sclient!=null)
+      sclient.cdocument = null;
+    sclient=null;
+    
+    super.finalize();
+  }
+  public Vector getUpdatedObjects() {
+    return updatedObjects;
+  }
 }