d72b43e332c4a3d199ee4f4a5c6ff727560ec7bb
[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
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     FileWatcher watcher = new FileWatcher(vsess.getVamsasFile());
95     long endtime=System.currentTimeMillis()+time;
96     try {
97       org.vamsas.client.simpleclient.Lock doclock;
98       watcher.setState();
99       do {
100         Thread.sleep(50); // tuning.
101         doclock=watcher.getChangedState();
102       } while (doclock==null && (time==0 || endtime>System.currentTimeMillis()));
103       if (doclock==null)
104         return null;
105       else {
106         doclock = vsess.getLock(doclock);
107         VamsasArchiveReader varc = new VamsasArchiveReader(vsess.getVamsasFile());
108         return _getReadonly(varc);
109       }
110     } catch (Exception e) {
111       log.error("Whilst watching file "+vsess.getVamsasFile(), e);
112     }
113     return null;
114   }
115
116   // from ClientDocument.getClientAppdata
117   private AppData[] getAppData(VamsasDocument doc) {
118     if (doc==null) {
119       log.debug("extractAppData called for null document object");
120       return null;
121     }
122     AppData appsGlobal=null, usersData=null;
123     Vector apldataset = AppDataReference.getUserandApplicationsData(
124         doc, this.getUserHandle(), this.getClientHandle());
125     if (apldataset!=null) {
126       if (apldataset.size()>0) {
127         AppData clientdat = (AppData) apldataset.get(0);
128         if (clientdat instanceof ApplicationData) {
129           appsGlobal = (ApplicationData) clientdat;
130           if (apldataset.size()>1) {
131             clientdat = (AppData) apldataset.get(1);
132             if (clientdat instanceof User) {
133               usersData = (User) clientdat;
134             }
135             if (apldataset.size()>2)
136               log.info("Ignoring additional ("+(apldataset.size()-2)+") AppDatas returned by document appdata query.");
137           } 
138         } else {
139           log.warn("Unexpected entry in AppDataReference query: id="+clientdat.getVorbaId()+" type="+clientdat.getClass().getName());
140         }
141         apldataset.removeAllElements(); // destroy references.
142       }
143     }
144     return new AppData[] { appsGlobal, usersData};
145   }
146   
147   protected ClientDoc _getReadonly(VamsasArchiveReader vreader) throws IOException, ValidationException, MarshalException {
148     valid();
149     if (vreader!=null) {
150       SimpleDocBinding docb = new SimpleDocBinding();
151       docb.setVorba(this);
152       VamsasDocument d;
153       d = docb.getVamsasDocument(vreader);
154       
155       if (d!=null) {
156         ClientDoc creader = new ClientDoc(d, null, vreader, getClientHandle().getClientUrn(), getProvenanceUser(), getVorbaIdHash());
157         return creader;
158       }
159     }
160     return null;
161   }  
162   /**
163    * from SimpleClient
164    * @return user field for a provenance entry
165    */
166   protected String getProvenanceUser() {
167     return new String(getUserHandle().getFullName()+" ["+getClientHandle().getClientUrn()+"]");
168   }
169   
170   public ClientDoc getUpdateable() {
171     valid();
172     try {
173       vsess.getLock();
174       VamsasArchive varc = new VamsasArchive(vsess, true, false); // read archive, write as vamsasDocument, don't erase original contents.
175       varc.setVorba(this);
176       VamsasDocument d = varc.getVamsasDocument(getProvenanceUser(), "Created new document.", VersionEntries.latestVersion()); // VAMSAS: provenance user and client combined
177       
178       if (d==null) {
179         log.warn("Backing out from opening a VamsasArchive writable IO session");
180         varc.cancelArchive();
181         return null;
182       }      
183       ClientDoc cdoc = new ClientDoc(d, varc, varc.getOriginalArchiveReader(), getClientHandle().getClientUrn(), getProvenanceUser(), getVorbaIdHash());
184       return cdoc;
185       // do appHandle?
186     } catch (Exception e) {
187       log.error("Failed to get Updateable version of "+vsess.getVamsasFile(), e);
188     }
189     return null;
190   }
191   /**
192    * trust client to not do anything stupid to the document roots which will now be written to the archive.
193    * @param cdoc
194    * @return true if write was a success.
195    */
196   public boolean doUpdate(ClientDoc cdoc) {
197     valid();
198     if (cdoc==null) {
199       log.warn("Invalid ClientDoc passed to org.vamsas.test.simpleclient.doUpdate()");
200       return false;
201     }
202     if (cdoc.iohandler==null) {
203       log.warn("Read only ClientDoc object passed to org.vamsas.test.simpleclient.doUpdate()");
204       return false;
205     }
206     if (cdoc.iohandler.getVorba()!=this) {
207       log.error("Mismatch between ClientDoc instances and ArchiveClient instances!");
208       return false;
209     }
210     try {
211       // do any appDatas first.
212       if (cdoc.iohandler.transferRemainingAppDatas())
213         log.debug("Remaining appdatas were transfered.");
214       cdoc.iohandler.putVamsasDocument(cdoc.doc);
215       cdoc.iohandler.closeArchive();
216       cdoc.iohandler=null;
217       cdoc = null;
218       vsess.unLock();
219     } catch (Exception e) {
220       log.warn("While updating archive in "+vsess.getVamsasFile(),e);
221       return false;
222     }
223     return true;
224   }
225   /**
226    * @param args
227    */
228   public static void usage() {
229     throw new Error("Usage: Username Organization VamsasFile [command,args]*");
230   }
231   public static void main(String[] args) {
232     // really simple.
233     if (args.length<3)
234       usage();
235     
236     ArchiveClient client = new ArchiveClient(args[0],args[1], new File(args[2]));
237     ClientDoc cdoc=null;
238     // sanity test.
239     try {
240       cdoc = client.getUpdateable();
241       // ArchiveReports.reportDocument(cdoc.doc, cdoc.getReader(), true, System.out);
242       System.out.println("Report Roots :");
243       ArchiveReports.rootReport(cdoc.getVamsasRoots(), true, System.out);
244       cdoc.addVamsasRoot(Core.getDemoVamsas());
245       System.out.println("Doing update.");
246       client.doUpdate(cdoc);
247       cdoc = null;
248       int u=5;
249       while (--u>0) {
250         System.out.println("Watch for more... ("+u+" left)");
251         cdoc = client.watch(0);
252         if (cdoc!=null) {
253           System.out.println("****\nUpdate detected at "+new Date());
254           ArchiveReports.reportDocument(cdoc.doc, cdoc.getReader(), true, System.out);
255         } else {
256           System.out.println("!!!! Null document update detected at "+new Date());
257         }
258       }
259     }
260     catch (Exception e) {
261       client.log.error("Broken!", e);
262     }
263     System.out.println("Finished at "+new Date());
264   }
265   public org.vamsas.client.Vobject getObject(VorbaId id) {
266     Hashtable idhash = this.getVorbaIdHash();
267     if (idhash!=null && idhash.containsKey(id))
268       return (Vobject) idhash.get(id);
269     return null;
270     }
271 }