updated test cases for spring 2006 schema, and major debug of locking system
[vamsas.git] / src / org / vamsas / test / simpleclient / ArchiveClient.java
1 /**
2  * 
3  */
4 package org.vamsas.test.simpleclient;
5
6 import java.io.File;
7 import java.io.IOException;
8 import java.util.Date;
9 import java.util.Hashtable;
10 import java.util.Vector;
11
12 import org.apache.commons.logging.Log;
13 import org.apache.commons.logging.LogFactory;
14 import org.exolab.castor.xml.MarshalException;
15 import org.exolab.castor.xml.ValidationException;
16 import org.vamsas.client.ClientHandle;
17 import org.vamsas.client.IVorbaIdFactory;
18 import org.vamsas.client.SessionHandle;
19 import org.vamsas.client.UserHandle;
20 import org.vamsas.client.Vobject;
21 import org.vamsas.client.VorbaId;
22 import org.vamsas.client.simpleclient.AppDataOutputStream;
23 import org.vamsas.client.simpleclient.FileWatcher;
24 import org.vamsas.client.simpleclient.IdFactory;
25 import org.vamsas.client.simpleclient.SessionFile;
26 import org.vamsas.client.simpleclient.SimpleDocBinding;
27 import org.vamsas.client.simpleclient.SimpleDocument;
28 import org.vamsas.client.simpleclient.VamsasArchive;
29 import org.vamsas.client.simpleclient.VamsasArchiveReader;
30 import org.vamsas.client.simpleclient.VamsasFile;
31 import org.vamsas.objects.core.AppData;
32 import org.vamsas.objects.core.ApplicationData;
33 import org.vamsas.objects.core.User;
34 import org.vamsas.objects.core.VamsasDocument;
35 import org.vamsas.objects.utils.AppDataReference;
36 import org.vamsas.objects.utils.DocumentStuff;
37 import org.vamsas.objects.utils.ProvenanceStuff;
38 import org.vamsas.objects.utils.SeqSet;
39 import org.vamsas.objects.utils.document.VersionEntries;
40 import org.vamsas.test.objects.Core;
41
42 /**
43  * @author jimp
44  *  test the VamsasFile routines for watching, reading and updating a vamsas document jar file.
45  *  simple document access base class.
46  */
47 public class ArchiveClient extends IdFactory {
48   
49   private Log log = LogFactory.getLog(ArchiveClient.class);
50   // protected UserHandle user=null;
51   // protected ClientHandle me = new ClientHandle("ArchiveClient","0.01");
52   VamsasFile vsess;
53   
54   /**
55    * @param user
56    * @param vsess
57    */
58   public ArchiveClient(UserHandle user, VamsasFile vsess) {
59     super(new SessionHandle("vamsasfile://"+vsess.getVamsasFile()), new ClientHandle("ArchiveClient","0.01"), user);
60     this.vsess = vsess;
61     valid();
62   }
63   private void _openVsess(File vsess) {
64     try {
65       this.vsess = new VamsasFile(vsess);
66     }
67     catch (Exception e) {
68       log.error("Couldn't open session for file "+vsess,e);
69       this.vsess = null;
70     }
71   }
72   public ArchiveClient(String username, String organization, File vsess) {
73     super(new SessionHandle("vamsasfile://"+vsess), new ClientHandle("ArchiveClient","0.01"), new UserHandle(username, organization));
74     _openVsess(vsess);
75     valid();
76   }
77   public ArchiveClient(String username, String organization, String clientName, String clientVersion, File vsess) {
78     super(new SessionHandle("vamsasfile://"+vsess), new ClientHandle(clientName, clientVersion), new UserHandle(username, organization));
79     _openVsess(vsess);
80     valid();
81   }
82   public void valid() {
83     if (vsess==null)
84       throw new Error("ArchiveClient instance is invalid!.");
85   }
86   public static int WATCH_SLEEP=300;
87   /**
88    * watch the document file for updates.
89    * @param time - length of time to watch for.
90    * @return read only IO interface for session document.
91    */
92   public ClientDoc watch(long time) {
93     valid();
94     vsess.unLock(); // doh.
95     FileWatcher watcher = new FileWatcher(vsess.getVamsasFile());
96     long endtime=System.currentTimeMillis()+time;
97     try {
98       org.vamsas.client.simpleclient.Lock doclock;
99       //watcher.setState();
100       do {
101         doclock=watcher.getChangedState();
102         if (doclock==null)
103           Thread.sleep(WATCH_SLEEP);
104       } while (doclock==null && (time==0 || endtime>System.currentTimeMillis())); // tuning.
105       if (doclock==null)
106         return null;
107       else {
108         doclock = vsess.getLock(doclock);
109         VamsasArchiveReader varc = new VamsasArchiveReader(vsess.getVamsasFile());
110         return _getReadonly(varc);
111       }
112     } catch (Exception e) {
113       log.error("Whilst watching file "+vsess.getVamsasFile(), e);
114     }
115     return null;
116   }
117
118   // from ClientDocument.getClientAppdata
119   private AppData[] getAppData(VamsasDocument doc) {
120     if (doc==null) {
121       log.debug("extractAppData called for null document object");
122       return null;
123     }
124     AppData appsGlobal=null, usersData=null;
125     Vector apldataset = AppDataReference.getUserandApplicationsData(
126         doc, this.getUserHandle(), this.getClientHandle());
127     if (apldataset!=null) {
128       if (apldataset.size()>0) {
129         AppData clientdat = (AppData) apldataset.get(0);
130         if (clientdat instanceof ApplicationData) {
131           appsGlobal = (ApplicationData) clientdat;
132           if (apldataset.size()>1) {
133             clientdat = (AppData) apldataset.get(1);
134             if (clientdat instanceof User) {
135               usersData = (User) clientdat;
136             }
137             if (apldataset.size()>2)
138               log.info("Ignoring additional ("+(apldataset.size()-2)+") AppDatas returned by document appdata query.");
139           } 
140         } else {
141           log.warn("Unexpected entry in AppDataReference query: id="+clientdat.getVorbaId()+" type="+clientdat.getClass().getName());
142         }
143         apldataset.removeAllElements(); // destroy references.
144       }
145     }
146     return new AppData[] { appsGlobal, usersData};
147   }
148   
149   protected ClientDoc _getReadonly(VamsasArchiveReader vreader) throws IOException, ValidationException, MarshalException {
150     valid();
151     if (vreader!=null) {
152       SimpleDocBinding docb = new SimpleDocBinding();
153       docb.setVorba(this);
154       VamsasDocument d;
155       d = docb.getVamsasDocument(vreader);
156       
157       if (d!=null) {
158         ClientDoc creader = new ClientDoc(d, null, vreader, getClientHandle().getClientUrn(), getProvenanceUser(), getVorbaIdHash());
159         return creader;
160       }
161     }
162     return null;
163   }  
164   /**
165    * from SimpleClient
166    * @return user field for a provenance entry
167    */
168   protected String getProvenanceUser() {
169     return new String(getUserHandle().getFullName()+" ["+getClientHandle().getClientUrn()+"]");
170   }
171   
172   public ClientDoc getUpdateable() {
173     valid();
174     try {
175       // patiently wait for a lock on the document.
176       long tries=5000;
177       org.vamsas.client.simpleclient.Lock lock;
178       while (((lock=vsess.getLock())==null || !lock.isLocked()) && --tries>0) {
179 //        Thread.sleep(1);
180         log.debug("Trying to get a document lock for the "+tries+"'th time.");
181       }
182       VamsasArchive varc = new VamsasArchive(vsess, true, false); // read archive, write as vamsasDocument, don't erase original contents.
183       varc.setVorba(this);
184       VamsasDocument d = varc.getVamsasDocument(getProvenanceUser(), "Created new document.", VersionEntries.latestVersion()); // VAMSAS: provenance user and client combined
185       
186       if (d==null) {
187         log.warn("Backing out from opening a VamsasArchive writable IO session");
188         varc.cancelArchive();
189         return null;
190       }      
191       ClientDoc cdoc = new ClientDoc(d, varc, varc.getOriginalArchiveReader(), getClientHandle().getClientUrn(), getProvenanceUser(), getVorbaIdHash());
192       return cdoc;
193       // do appHandle?
194     } catch (Exception e) {
195       log.error("Failed to get Updateable version of "+vsess.getVamsasFile(), e);
196     }
197     return null;
198   }
199   /**
200    * trust client to not do anything stupid to the document roots which will now be written to the archive.
201    * @param cdoc
202    * @return true if write was a success.
203    */
204   public boolean doUpdate(ClientDoc cdoc) {
205     valid();
206     if (cdoc==null) {
207       log.warn("Invalid ClientDoc passed to org.vamsas.test.simpleclient.doUpdate()");
208       return false;
209     }
210     if (cdoc.iohandler==null) {
211       log.warn("Read only ClientDoc object passed to org.vamsas.test.simpleclient.doUpdate()");
212       return false;
213     }
214     if (cdoc.iohandler.getVorba()!=this) {
215       log.error("Mismatch between ClientDoc instances and ArchiveClient instances!");
216       return false;
217     }
218     try {
219       // do any appDatas first.
220       if (cdoc.iohandler.transferRemainingAppDatas())
221         log.debug("Remaining appdatas were transfered.");
222       cdoc.updateDocumentRoots();
223       cdoc.iohandler.putVamsasDocument(cdoc.doc);
224       cdoc.iohandler.closeArchive();
225       cdoc.iohandler=null;
226       cdoc = null;
227       vsess.unLock();
228     } catch (Exception e) {
229       log.warn("While updating archive in "+vsess.getVamsasFile(),e);
230       return false;
231     }
232     return true;
233   }
234   /**
235    * @param args
236    */
237   public static void usage() {
238     throw new Error("Usage: Username Organization VamsasFile [command,args]*");
239   }
240   public static void main(String[] args) {
241     // really simple.
242     if (args.length<3)
243       usage();
244     
245     ArchiveClient client = new ArchiveClient(args[0],args[1], new File(args[2]));
246     ClientDoc cdoc=null;
247     // sanity test.
248     try {
249       cdoc = client.getUpdateable();
250       // ArchiveReports.reportDocument(cdoc.doc, cdoc.getReader(), true, System.out);
251       System.out.println("Report Roots :");
252       ArchiveReports.rootReport(cdoc.getVamsasRoots(), true, System.out);
253       cdoc.addVamsasRoot(Core.getDemoVamsas());
254       System.out.println("Doing update.");
255       client.doUpdate(cdoc);
256       cdoc.closeDoc();
257       cdoc = null;
258       int u=5;
259       while (--u>0) {
260         System.out.println("Watch for more... ("+u+" left)");
261         ClientDoc ucdoc = client.watch(50000);
262         if (ucdoc!=null) {
263           System.out.println("****\nUpdate detected at "+new Date());
264           ArchiveReports.reportDocument(ucdoc.doc, ucdoc.getReader(), true, System.out);
265           ucdoc.closeDoc();
266           ucdoc=null;
267         } else {
268           System.out.println("!!!! Null document update detected at "+new Date());
269         }
270       }
271     }
272     catch (Exception e) {
273       client.log.error("Broken!", e);
274     }
275     System.out.println("Finished at "+new Date());
276   }
277   public org.vamsas.client.Vobject getObject(VorbaId id) {
278     Hashtable idhash = this.getVorbaIdHash();
279     if (idhash!=null && idhash.containsKey(id))
280       return (Vobject) idhash.get(id);
281     return null;
282     }
283 }