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