intermediate cjeckin - nfs woes!
[vamsas.git] / src / org / vamsas / client / simpleclient / ClientDocument.java
index a6bb78c..6b1d7fc 100644 (file)
@@ -3,78 +3,60 @@
  */
 package org.vamsas.client.simpleclient;
 
-import java.util.Hashtable;
 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.Vobject;
 import org.vamsas.client.VorbaId;
-import org.vamsas.client.object;
-import org.vamsas.objects.core.AppData;
 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;
 
 /**
- * @author jimp Contains a collection of vamsas objects and reference to a
- *         specified ClientHandle's information.
+ * Maintains a collection of vamsas objects, appdatas and states, and provides api for a SimpleClient's client.
+ * @author jimp 
  */
 public class ClientDocument extends org.vamsas.client.ClientDocument implements IClientDocument {
   private static Log log = LogFactory.getLog(ClientDocument.class);
   private VamsasDocument doc;
-  protected IClient vorba;
-  protected ApplicationData appsglobal=null;
-  protected User usersdata=null;
-  protected byte[] appData=null;
+  protected SimpleClient sclient;
   protected VamsasArchive archive = null;
   /**
+   * indicate if new data has been incorporated
+   */
+  private boolean isModified = false;
+  /**
+   * Public method for internal use by SimpleClient.
+   * @return true if document has been modified.
+   */
+  public boolean isModified() {
+    return isModified;
+  }
+  private java.util.Hashtable objrefs=null;
+  /**
    *
    *  prepare Application-side dataset from the vamsas Document archive
    * @param doc - the dataset
    * @param docHandler - the sessionFile IO handler
    * @param Factory - the source of current and new vorbaIds
-   * @param vorba - the client instance
+   * @param sclient - the simpleclient instance
    */
-  protected ClientDocument(VamsasDocument doc, VamsasArchive docHandler, IdFactory Factory, IClient vorba) {
+  protected ClientDocument(VamsasDocument doc, VamsasArchive docHandler, IdFactory Factory, SimpleClient sclient) {
     super(Factory.getVorbaIdHash(), Factory);
     
     /**
      * prepare Application-side dataset from the vamsas Document archive
      */
-    this.vorba = vorba;
+    this.sclient = sclient;
     archive = docHandler;
     this.doc = doc;
-    extractAppData();
-  }
-  /**
-   * gets appropriate app data for the application, if it exists in this dataset
-   * 
-   */
-  private void extractAppData() {
-    Vector apldataset = AppDataReference.getUserandApplicationsData(
-        doc, vorbafactory.getUserHandle(), vorbafactory.getClientHandle());
-    if (apldataset!=null) {
-      if (apldataset.size()>0) {
-        AppData clientdat = (AppData) apldataset.get(0);
-        if (clientdat instanceof ApplicationData) {
-          appsglobal = (ApplicationData) clientdat;
-          if (apldataset.size()>1) {
-            clientdat = (AppData) apldataset.get(1);
-            if (clientdat instanceof User)
-              usersdata = (User) clientdat;
-            if (apldataset.size()>2)
-              log.info("Ignoring additional ("+(apldataset.size()-2)+") AppDatas returned by document appdata query.");
-          } 
-        } else {
-          log.warn("Unexpected entry in AppDataReference query: id="+clientdat.getVorbaId()+" type="+clientdat.getClass().getName());
-        }
-      }
-    }
+    objrefs = Factory.getVorbaIdHash();
   }
   
   /*
@@ -82,9 +64,10 @@ public class ClientDocument extends org.vamsas.client.ClientDocument implements
    * 
    * @see org.vamsas.client.IClientDocument#getObject(org.vamsas.client.VorbaId)
    */
-  public object getObject(VorbaId id) {
-    // TODO: look up id in document object
-    // retrieve object and return
+  public Vobject getObject(VorbaId id) {
+    if (objrefs.containsKey(id))
+      return (Vobject) objrefs.get(id);
+    log.debug("Returning null Vobject reference for id "+id.getId());
     return null;
   }
   
@@ -93,27 +76,78 @@ public class ClientDocument extends org.vamsas.client.ClientDocument implements
    * 
    * @see org.vamsas.client.IClientDocument#getObjects(org.vamsas.client.VorbaId[])
    */
-  public object[] getObjects(VorbaId[] ids) {
-    // TODO: getObject in bulk
-    return null;
+  public Vobject[] getObjects(VorbaId[] ids) {
+    Vobject[] vo = new Vobject[ids.length];
+    for (int i=0,j=ids.length; i<j;i++) 
+      if (objrefs.containsKey(ids[i]))
+        vo[i] = (Vobject) objrefs.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
+   */
+  private VAMSAS[] _VamsasRoots=null;
   /*
    * (non-Javadoc)
-   * 
+   * 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)
    * @see org.vamsas.client.IClientDocument#getVamsasRoots()
    */
   public VAMSAS[] getVamsasRoots() {
-    if (doc.getVAMSAS() == null)
+    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
-      return new VAMSAS[] { new VAMSAS() };
-    return doc.getVAMSAS();
+      _VamsasRoots = new VAMSAS[] { new VAMSAS() };
+    } else {
+      _VamsasRoots = new VAMSAS[roots.length];
+      for (int r=0;r<roots.length; r++)
+        _VamsasRoots[r] = roots[r];
+    }
+    return _VamsasRoots;
   }
   
-  /**
-   * update the document with new roots.
-   */
-  public void setVamsasRoots(VAMSAS[] newroots) {
+  private int _contains(VAMSAS root, VAMSAS[] docRoots) {
+    if (root==null)
+      return -1;
+    if (docRoots==null || docRoots.length==0)
+      return -1;
+    String r_id = root.getId();
+    for (int i=0,j=docRoots.length; i<j; i++)
+      if (docRoots[i]==root || (docRoots[i]!=null && docRoots[i].getId().equals(r_id)))
+        return i;
+    return -1;
+  }
+/**
+ * verify that newr version is really an intact version of the 
+ * @param newVersion (may be modified)
+ * @param oldVersion 
+ * @return true if newVersion is a valid root that preserves original references
+ */
+  private boolean isValidUpdate(VAMSAS newVersion, final VAMSAS oldVersion) {
+    // 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.
+      if (!newVersion.isRegistered())
+        _registerObject(newVersion);
+      // Should retrieve original version and compare - unless local hashes can be used to determine if resultSet has been truncated.
+      // just do internal validation for moment.
+      if (newVersion.isValid())
+        return true;
+      return false;
+    } else {
+      // redundant ? if (oldVersion.is__stored_in_document())
+      if (!newVersion.isRegistered())
+        _registerObject(newVersion);
+      if (newVersion.isValid())
+        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
@@ -125,78 +159,259 @@ public class ClientDocument extends org.vamsas.client.ClientDocument implements
       for (int i = 0, k = newroots.length; i < k; i++) {
         if (newroots[i].isRegistered()) {
           // easy - just check if anything has changed and do provenance
-          object oldversion = getObject(newroots[i].getVorbaId());
+          Vobject oldversion = getObject(newroots[i].getVorbaId());
           if (oldversion instanceof VAMSAS) {
-            // LATER: appropriate merging behaviour when two clients have
-            // modified the same registered object independently
+            // 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 object since last retrieval.
+              // client has modified this Vobject since last retrieval.
               if (newroots[i].get__last_hash() != oldversion.get__last_hash()) {
-                // object has been modified by another client since this
+                // 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 object "
+                "SimpleClient error when using setVamsasRoots : The vorbaId for Vobject "
                 + i
-                + " does not refer to an object of type VAMSAS in the current document!");
+                + " does not refer to an Vobject of type VAMSAS in the current document!");
           }
         } else {
           if (!newroots[i].is__stored_in_document()) {
-            // check if object is modified
+            // check if Vobject is modified
             if (newroots[i].get__last_hash() != newroots[i].hashCode()) {
-              // it is - so we add newroots[i] as a new object, with updated
+              // 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 object in the document
+            // just add newroots[i] as a new Vobject in the document
             // - with appropriate provenance.
           }
         }
+      }*/
+  }
+  /**
+   * merge old and new root vectors
+   * @param newr This array may be written to
+   * @param original
+   * @param the client document (usually this) which this root set belongs to.
+   * @return merged vector of vamsas roots
+   */
+  private VAMSAS[] _combineRoots(VAMSAS[] newr, final VAMSAS[] original, ClientDocument modflag) {
+    Vector rts = new Vector();
+    boolean modified=false;
+    for (int i=0,j=original.length; i<j; i++) {
+      int k = _contains(original[i], newr);
+      if (k>-1) {
+        if (isValidUpdate(newr[k], original[i])) {
+          modified=true;
+          rts.add(newr[k]);
+          newr[k]=null;
+        } else {
+          // LATER: try harder to merge ducument roots.
+          log.warn("Couldn't merge new VAMSAS root "+newr[k].getId());
+          newr[k] = null; // LATER: this means we ignore mangled roots. NOT GOOD
+        }
+      } else {
+        // add in order.
+        rts.add(original[i]);
+      }
+    }
+    // add remaining (new) roots
+    for (int i=0,j=newr.length; i<j; i++) {
+      if (newr[i]!=null) {
+        rts.add(newr[i]);
+        modified=true;
       }
     }
+    newr = new VAMSAS[rts.size()];
+    for (int i=0,j=rts.size(); i<j; i++)
+      newr[i] = (VAMSAS) rts.get(i);
+    if (modflag!=null)
+      modflag.isModified = modified;
+    return newr;
   }
   
+  /**
+   * 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) {
+    VAMSAS[] newr;
+    if (newroots==null) {
+      log.debug("setVamsasRoots(null) - do nothing.");
+      return;
+    }
+    // are we dealing with same array ?
+    if (_VamsasRoots!=newroots) {
+      // 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) {
-    // TODO Auto-generated method stub
-    
+    VAMSAS[] newroots = _combineRoots(new VAMSAS[] {newroot}, _VamsasRoots, this);
+    _VamsasRoots = newroots;  
   }
   
   /*
    * (non-Javadoc)
    * 
-   * @see org.vamsas.client.IClientDocument#registerObjects(org.vamsas.client.object[])
+   * @see org.vamsas.client.IClientDocument#registerObjects(org.vamsas.client.Vobject[])
    */
-  public VorbaId[] registerObjects(object[] unregistered) {
+  public VorbaId[] registerObjects(Vobject[] unregistered) {
     if (unregistered!=null) {
       VorbaId ids[] = new VorbaId[unregistered.length];
       for (int i=0,k=unregistered.length; i<k; i++)
-        ids[i]=registerObject(unregistered[i]);
+        if (unregistered[i]!=null) {
+          log.warn("Null Vobject passed to registerObject[] at position "+i);
+          return null;
+        } else {
+          ids[i]=registerObject(unregistered[i]);
+        }
+      log.debug("Registered "+unregistered.length+" objects - total of "+objrefs.size()+" ids.");
       return ids;
     }
     return null;
   }
-  
   /* (non-Javadoc)
-   * @see org.vamsas.client.IClientDocument#registerObject(org.vamsas.client.object)
+   * @see org.vamsas.client.IClientDocument#registerObject(org.vamsas.client.Vobject)
    */
-  public VorbaId registerObject(object unregistered) {
-    // TODO: add provenance stuff to newly registered object
-    return _registerObject(unregistered);
+  public VorbaId registerObject(Vobject unregistered) {
+    if (unregistered!=null) {
+      VorbaId id = _registerObject(unregistered);
+      log.debug("Registered object - total of "+objrefs.size()+" ids.");
+      return id;
+    }
+    log.warn("Null Vobject passed to registerObject.");
+    return null;
   }
+  /**
+   * IClientAppdata instance - if it exists.
+   */
+  SimpleClientAppdata scappd = null;
   /* (non-Javadoc)
    * @see org.vamsas.client.IClientDocument#getClientAppdata()
    */
   public IClientAppdata getClientAppdata() {
-    // TODO Auto-generated method stub
+    if (scappd==null) {
+      log.debug("Creating new SimpleClientAppdata instance for "+sclient.getSessionHandle());
+      scappd = new SimpleClientAppdata(this);
+      if (scappd==null) {
+        // LATER: may not need this as a warning message.
+        log.warn("Null appdata object for "+sclient.getSessionHandle());
+      } else {
+        log.debug("Created SimpleClientAppdata successfully.");
+      }
+    } else {
+      log.debug("Returning existing SimpleClientAppdata reference.");
+    }
+    return scappd;
+  }
+  /**
+   * access the vamsas document
+   * @return the session's vamsas document
+   */
+  protected VamsasDocument getVamsasDocument() {
+    return doc;
+  }
+  /**
+   * returns the read-only IO interface for the vamsas document Jar file
+   * @return
+   */
+  protected VamsasArchiveReader getVamsasArchiveReader() {
+    try {
+      return archive.getOriginalArchiveReader();
+    } catch (Exception e) {
+      log.warn("Unable to create OriginalArchiveReader!", e);
+    }
     return null;
   }
+  protected boolean updateSessionDocument() throws java.io.IOException {
+    if (!isModified() && !scappd.isModified())
+      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;
+      scappd.closeForWriting();      
+      long newAppd = scappd.newAppData.sessionFile.length();
+      
+      if (scappd.appsGlobal==null) {
+        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()));
+      }
+      if (scappd.newAppData!=null && scappd.newAppData.sessionFile.exists()) {
+        if (scappd.appsGlobal.getData()!=null) {
+          scappd.appsGlobal.setData(null);
+          scappd.appsGlobal.setDataReference(AppDataReference.uniqueAppDataReference(doc, sclient.client.getClientUrn()));
+        }
+        
+          
+          
+      }
+      if (scappd.usersData==null) {
+        
+      }
+      
+    }
+    cdocument.archive.putVamsasDocument(vdoc);
+    // write the appHandle to the lastupdate file.
+  }
+  if (scappd!=null) {
+      if (scappd.accessedDocument)
+    }
+    va = new org.vamsas.client.simpleclient.VamsasArchive(newf, false, true, sfile);
+    doc = va.getVamsasDocument();
+    doc.addVAMSAS(Core.getDemoVamsas());
+    doc.addApplicationData(makeDemoAppdata(va, 
+        "org.vamsas.test.simpleclient.VamsasArchive", "another old Bugger esq", "rescinded"));
+    if (va.transferRemainingAppDatas())
+      log.info("Remain appdatas were transferred.");
+    else
+      log.warn("No appdatas were transferred. This is wrong.");
+    va.putVamsasDocument(doc);
+    va.closeArchive();
+
+    return true; // successfully updated.
+  }
+  /* (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;
+    }
+    // TODO local garbage collection
+    super.finalize();
+  }
+
 }