package org.vamsas.test.simpleclient;
import java.io.File;
+import java.io.IOException;
+import java.util.Date;
+import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
+import org.exolab.castor.xml.MarshalException;
+import org.exolab.castor.xml.ValidationException;
import org.vamsas.client.ClientHandle;
+import org.vamsas.client.IVorbaIdFactory;
+import org.vamsas.client.SessionHandle;
import org.vamsas.client.UserHandle;
+import org.vamsas.client.simpleclient.AppDataOutputStream;
import org.vamsas.client.simpleclient.FileWatcher;
+import org.vamsas.client.simpleclient.IdFactory;
import org.vamsas.client.simpleclient.SessionFile;
+import org.vamsas.client.simpleclient.SimpleDocBinding;
+import org.vamsas.client.simpleclient.SimpleDocument;
import org.vamsas.client.simpleclient.VamsasArchive;
+import org.vamsas.client.simpleclient.VamsasArchiveReader;
import org.vamsas.client.simpleclient.VamsasFile;
+import org.vamsas.objects.core.AppData;
+import org.vamsas.objects.core.ApplicationData;
+import org.vamsas.objects.core.User;
+import org.vamsas.objects.core.VamsasDocument;
+import org.vamsas.objects.utils.AppDataReference;
+import org.vamsas.objects.utils.DocumentStuff;
+import org.vamsas.objects.utils.ProvenanceStuff;
+import org.vamsas.objects.utils.SeqSet;
+import org.vamsas.objects.utils.document.VersionEntries;
+import org.vamsas.test.objects.Core;
/**
* @author jimp
* test the VamsasFile routines for watching, reading and updating a vamsas document jar file.
+ * simple document access base class.
*/
-public class ArchiveClient {
- Log log = LogFactory.getLog(ArchiveClient.class);
- UserHandle user=null;
- ClientHandle me = new ClientHandle("ArchiveClient","0.01");
+public class ArchiveClient extends IdFactory {
+
+ private Log log = LogFactory.getLog(ArchiveClient.class);
+ // protected UserHandle user=null;
+ // protected ClientHandle me = new ClientHandle("ArchiveClient","0.01");
VamsasFile vsess;
/**
* @param vsess
*/
public ArchiveClient(UserHandle user, VamsasFile vsess) {
- super();
- this.user = user;
+ super(new SessionHandle("vamsasfile://"+vsess.getVamsasFile()), new ClientHandle("ArchiveClient","0.01"), user);
this.vsess = vsess;
+ valid();
}
- public ArchiveClient(String username, String organization, String vsess) {
- super();
- this.user = new UserHandle(username, organization);
+ private void _openVsess(File vsess) {
try {
- this.vsess = new VamsasFile(new File(vsess));
- } catch (Exception e) {
- log.error("Couldn't open session on file "+vsess,e);
- this.vsess=null;
+ this.vsess = new VamsasFile(vsess);
}
+ catch (Exception e) {
+ log.error("Couldn't open session for file "+vsess,e);
+ this.vsess = null;
+ }
+ }
+ public ArchiveClient(String username, String organization, File vsess) {
+ super(new SessionHandle("vamsasfile://"+vsess), new ClientHandle("ArchiveClient","0.01"), new UserHandle(username, organization));
+ _openVsess(vsess);
+ valid();
+ }
+ public ArchiveClient(String username, String organization, String clientName, String clientVersion, File vsess) {
+ super(new SessionHandle("vamsasfile://"+vsess), new ClientHandle(clientName, clientVersion), new UserHandle(username, organization));
+ _openVsess(vsess);
+ valid();
}
public void valid() {
if (vsess==null)
throw new Error("ArchiveClient instance is invalid!.");
}
+
/**
- *
+ * watch the document file for updates.
* @param time - length of time to watch for.
- * @return IO interface for session document.
+ * @return read only IO interface for session document.
*/
- public VamsasArchive watch(long time) {
+ public ClientDoc watch(long time) {
+ valid();
+ FileWatcher watcher = new FileWatcher(vsess.getVamsasFile());
+ long endtime=System.currentTimeMillis()+time;
+ try {
+ org.vamsas.client.simpleclient.Lock doclock;
+ watcher.setState();
+ do {
+ Thread.sleep(50); // tuning.
+ doclock=watcher.getChangedState();
+ } while (doclock==null && (time==0 || endtime>System.currentTimeMillis()));
+ if (doclock==null)
+ return null;
+ else {
+ doclock = vsess.getLock(doclock);
+ VamsasArchiveReader varc = new VamsasArchiveReader(vsess.getVamsasFile());
+ return _getReadonly(varc);
+ }
+ } catch (Exception e) {
+ log.error("Whilst watching file "+vsess.getVamsasFile(), e);
+ }
+ return null;
+ }
+
+ // from ClientDocument.getClientAppdata
+ private AppData[] getAppData(VamsasDocument doc) {
+ if (doc==null) {
+ log.debug("extractAppData called for null document object");
+ return null;
+ }
+ AppData appsGlobal=null, usersData=null;
+ Vector apldataset = AppDataReference.getUserandApplicationsData(
+ doc, this.getUserHandle(), this.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());
+ }
+ apldataset.removeAllElements(); // destroy references.
+ }
+ }
+ return new AppData[] { appsGlobal, usersData};
+ }
+
+ protected ClientDoc _getReadonly(VamsasArchiveReader vreader) throws IOException, ValidationException, MarshalException {
valid();
- // wait around watching for a change.
- VamsasArchive varch=null;
- // FileWatcher w = new FileWatcher(vsess);
- return varch;
+ if (vreader!=null) {
+ SimpleDocBinding docb = new SimpleDocBinding();
+ docb.setVorba(this);
+ VamsasDocument d;
+ d = docb.getVamsasDocument(vreader);
+
+ if (d!=null) {
+ ClientDoc creader = new ClientDoc(d, null, vreader, getProvenanceUser());
+ return creader;
+ }
+ }
+ return null;
+ }
+ /**
+ * from SimpleClient
+ * @return user field for a provenance entry
+ */
+ protected String getProvenanceUser() {
+ return new String(getUserHandle().getFullName()+" ["+getClientHandle().getClientUrn()+"]");
}
+ public ClientDoc getUpdateable() {
+ valid();
+ try {
+ vsess.getLock();
+ VamsasArchive varc = new VamsasArchive(vsess, true, false); // read archive, write as vamsasDocument, don't erase original contents.
+ varc.setVorba(this);
+ VamsasDocument d = varc.getVamsasDocument(getProvenanceUser(), "Created new document.", VersionEntries.latestVersion()); // VAMSAS: provenance user and client combined
+
+ if (d==null) {
+ log.warn("Backing out from opening a VamsasArchive writable IO session");
+ varc.cancelArchive();
+ return null;
+ }
+ ClientDoc cdoc = new ClientDoc(d, varc, varc.getOriginalArchiveReader(), getProvenanceUser());
+ return cdoc;
+ // do appHandle?
+ } catch (Exception e) {
+ log.error("Failed to get Updateable version of "+vsess.getVamsasFile(), e);
+ }
+ return null;
+ }
+ /**
+ * trust client to not do anything stupid to the document roots which will now be written to the archive.
+ * @param cdoc
+ * @return true if write was a success.
+ */
+ public boolean doUpdate(ClientDoc cdoc) {
+ valid();
+ if (cdoc==null) {
+ log.warn("Invalid ClientDoc passed to org.vamsas.test.simpleclient.doUpdate()");
+ return false;
+ }
+ if (cdoc.iohandler==null) {
+ log.warn("Read only ClientDoc object passed to org.vamsas.test.simpleclient.doUpdate()");
+ return false;
+ }
+ if (cdoc.iohandler.getVorba()!=this) {
+ log.error("Mismatch between ClientDoc instances and ArchiveClient instances!");
+ return false;
+ }
+ try {
+ // do any appDatas first.
+ if (cdoc.iohandler.transferRemainingAppDatas())
+ log.debug("Remaining appdatas were transfered.");
+ cdoc.iohandler.putVamsasDocument(cdoc.doc);
+ cdoc.iohandler.closeArchive();
+ cdoc.iohandler=null;
+ cdoc = null;
+ vsess.unLock();
+ } catch (Exception e) {
+ log.warn("While updating archive in "+vsess.getVamsasFile(),e);
+ return false;
+ }
+ return true;
+ }
/**
* @param args
*/
// really simple.
if (args.length<3)
usage();
- ArchiveClient client = new ArchiveClient(args[0],args[1], args[2]);
+ ArchiveClient client = new ArchiveClient(args[0],args[1], new File(args[2]));
+ ClientDoc cdoc=null;
+ // sanity test.
+ try {
+ cdoc = client.getUpdateable();
+ // ArchiveReports.reportDocument(cdoc.doc, cdoc.getReader(), true, System.out);
+ System.out.println("Report Roots :");
+ ArchiveReports.rootReport(cdoc.getVamsasRoots(), true, System.out);
+ cdoc.addVamsasRoot(Core.getDemoVamsas());
+ System.out.println("Doing update.");
+ client.doUpdate(cdoc);
+ cdoc = null;
+ int u=5;
+ while (--u>0) {
+ System.out.println("Watch for more... ("+u+" left)");
+ cdoc = client.watch(0);
+ if (cdoc!=null) {
+ System.out.println("****\nUpdate detected at "+new Date());
+ ArchiveReports.reportDocument(cdoc.doc, cdoc.getReader(), true, System.out);
+ } else {
+ System.out.println("!!!! Null document update detected at "+new Date());
+ }
+ }
+ }
+ catch (Exception e) {
+ client.log.error("Broken!", e);
+ }
+ System.out.println("Finished at "+new Date());
}
}
--- /dev/null
+package org.vamsas.test.simpleclient;
+
+import java.util.Vector;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.vamsas.client.VorbaId;
+import org.vamsas.client.simpleclient.ClientDocument;
+import org.vamsas.client.simpleclient.VamsasArchive;
+import org.vamsas.client.simpleclient.VamsasArchiveReader;
+import org.vamsas.objects.core.Entry;
+import org.vamsas.objects.core.VAMSAS;
+import org.vamsas.objects.core.VamsasDocument;
+import org.vamsas.objects.utils.ProvenanceStuff;
+
+// simple holder to pass to client.
+public class ClientDoc {
+ protected boolean isModified=false;
+ private Log log = LogFactory.getLog(ClientDoc.class);
+ protected VamsasDocument doc;
+ public org.vamsas.objects.core.VAMSAS[] _VamsasRoots;
+ protected VamsasArchive iohandler=null;
+ protected VamsasArchiveReader reader=null;
+ private String user=null;
+
+ /**
+ * @param doc
+ * @param iohandler
+ * @param reader
+ * @param user
+ */
+ public ClientDoc(VamsasDocument doc, VamsasArchive iohandler, VamsasArchiveReader reader, String user) {
+ super();
+ this.doc = doc;
+ this.iohandler = iohandler;
+ this.reader = reader;
+ this.user = user;
+ _VamsasRoots = doc.getVAMSAS();
+ }
+ // AppDataOutputStream appd;
+ //AppDataOutputStream userd;
+ /* (non-Javadoc)
+ * @see java.lang.Object#finalize()
+ */
+ protected Entry getProvenanceEntry(String action) {
+ // VAMSAS: modify schema to allow referencing of user field (plus other issues, ClientUrn field, machine readable action, input parameters, additional data generated notes
+ Entry prov = ProvenanceStuff.newProvenanceEntry(user, action);
+ return prov;
+ }
+ public VAMSAS[] getVamsasRoots() {
+ if (doc==null) {
+ log.debug("Null document for getVamsasRoots(), returning null");
+ return null;
+ }
+ if (iohandler==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 to get filled.
+ _VamsasRoots = new VAMSAS[] { new VAMSAS() };
+ // Do provenance now. just in case.
+ doc.getProvenance().addEntry(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++)
+ _VamsasRoots[r] = roots[r];
+ }
+ return _VamsasRoots;
+ }
+
+ private int _contains(VAMSAS root, VAMSAS[] docRoots) {
+ if (root==null)
+ return -1;
+ if (docRoots==null || docRoots.length==0)
+ return -1;
+ VorbaId r_id = root.getVorbaId();
+ for (int i=0,j=docRoots.length; i<j; i++) {
+ VorbaId n_id=null;
+ if (docRoots[i]==root || (docRoots[i]!=null && (n_id=docRoots[i].getVorbaId())!=null && n_id.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())
+ iohandler.getVorba().makeVorbaId(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())
+ iohandler.getVorba().makeVorbaId(newVersion);
+ if (newVersion.isValid())
+ return true;
+ }
+ return false;
+ }
+ /**
+ /**
+ * 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, ClientDoc 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) {
+ 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 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;
+ }
+
+ public VamsasArchiveReader getReader() {
+ return reader;
+ }
+ protected void finalize() throws Throwable {
+ super.finalize();
+ //if (reader!=null)
+ // reader.close();
+ //reader=null;
+// if (iohandler!=null) {
+// iohandler.cancelArchive(); // otherwise the original may be overwritten.
+// }
+ }
+
+}
\ No newline at end of file