formatting changes
[vamsas.git] / src / uk / ac / vamsas / test / ExampleApplication.java
1 package uk.ac.vamsas.test;
2
3 import uk.ac.vamsas.client.*;
4 import uk.ac.vamsas.client.picking.IMessageHandler;
5 import uk.ac.vamsas.client.picking.IPickManager;
6 import uk.ac.vamsas.client.picking.Message;
7 import uk.ac.vamsas.objects.core.VAMSAS;
8 import uk.ac.vamsas.test.objects.Core;
9
10 import java.awt.Event;
11 import java.beans.PropertyChangeEvent;
12 import java.beans.PropertyChangeListener;
13 import java.io.DataInput;
14 import java.io.DataInputStream;
15 import java.io.DataOutputStream;
16 import java.io.File;
17 import java.io.IOException;
18 import java.io.InputStream;
19 import java.io.ObjectInputStream;
20 import java.io.ObjectOutputStream;
21 import java.io.OutputStream;
22 import java.util.Vector;
23
24 /**
25  * Toy vamsas command line client application demonstrating the API. 
26  * Currently runs with one argument: ExampleApplication.main(new String("watch"))
27  * Test: Start up at least two of these processes independently and they will 
28  * successively modify and handle update events from the document model.
29  * 
30  * Behaviour of each client:
31  * Event handlers are registered for documentUpdate.
32  * - every document update:
33  *   * the vamsas document will be dumped to standard out using uk.ac.vamsas.test.simpleclient.ArchiveReports
34  *   * if there are more than 4 vamsas roots, the first sequence in the first alignment of the first dataset of the second vamsas root will be appended with a single gap character and then written back to the session document. 
35  * A pick thread is started, which sends random CUSTOM pick events every so often (tuning: flooding the pick channel seems to affect the behaviour of other vamsasClient threads, suggesting some object lock contention).
36  * A new vamsas root generated from uk.ac.vamsas.test.objects.Core.getDemoVamsas is added to the document.
37  * Then a while loop waits around for events until shutdown:
38  *  - currently it will shutdown after 9 updates (totalUpdates)
39  *  - an update will be made after every other update that is detected.
40  * 
41  * Status: PickManager now shuts down correctly. Serial updates for two
42  * instances work correctly and are detected under j1.4 (need to test in 1.5 and
43  * 1.6).
44  * 
45  * TODO: test appData get/set methods
46  * 
47  * TODO: verify and test pickManager and interaction between it and other
48  * session events
49  * 
50  * TODO: add more session interaction events
51  * 
52  * TODO: test client add/leave events - currently library generates exceptions
53  * for sessionlist and clientlist modifications.
54  * 
55  * @author jimp
56  */
57
58 public class ExampleApplication {
59   private ClientHandle app;
60
61   private UserHandle user; // TODO: make this something defined by the
62
63   // api
64
65   private IClientFactory clientfactory;
66
67   private IClient vorbaclient;
68
69   private byte[] mydata;
70
71   private Vector vamsasObjects;
72
73   private boolean isUpdated = false;
74
75   private boolean isShuttingdown = false;
76
77   private boolean isFinalizing = false;
78
79   private int totalUpdates = 9;
80
81   private uk.ac.vamsas.client.VorbaId recover = null;
82
83   private int calls = 0;
84
85   private long mdatahash = 0;
86
87   private long muserdatahash = 0;
88
89   private void processVamsasDocument(IClientDocument doc) {
90     if (doc.getVamsasRoots().length < 4) {
91       doc.addVamsasRoot(Core.getDemoVamsas());
92     } else {
93       try {
94         uk.ac.vamsas.objects.core.DataSet ds = doc.getVamsasRoots()[1]
95             .getDataSet(0);
96         uk.ac.vamsas.objects.core.AlignmentSequence alsq = ds.getAlignment(0)
97             .getAlignmentSequence(0);
98         if (recover == null) {
99           recover = alsq.getVorbaId();
100         } else {
101           Vobject recoverd = doc.getObject(recover);
102           System.out.println("Recovery of " + recover + " was "
103               + ((recoverd == null) ? "A FAILURE" : "SUCCESSFUL"));
104         }
105         System.out.println("Modifying Sequence:\n" + alsq.hashCode());
106         alsq.setSequence(alsq.getSequence() + ds.getAlignment(0).getGapChar());
107         System.out.println("Modifying Sequence:\n" + alsq.hashCode());
108         System.out.println("Modified Sequence:\n" + alsq.getSequence());
109         doc.setVamsasRoots(doc.getVamsasRoots());
110       } catch (Exception ee) {
111
112       }
113     }
114     // get this apps 'mydata' if it hasn't got it already.
115     System.out.println("Trying to get appdata and modify it.....");
116     try {
117       processAppData(doc);
118       System.out.println(".....Finished.");
119     } catch (Exception e) {
120       System.err.println("Failed to process appdata for our application.");
121       e.printStackTrace(System.err);
122     }
123
124     // .. access this application's 'public' mydata' if there is any.
125     vorbaclient.updateDocument(doc);
126     // merge vamsasObjects with vamsas objects in document
127
128   }
129
130   private int appdatareads = 0;
131
132   private void processAppData(IClientDocument doc) throws Exception {
133     appdatareads++;
134     boolean writtenonce = false;
135     if (doc != null) {
136       uk.ac.vamsas.client.IClientAppdata appd = doc.getClientAppdata();
137       if (appd.hasClientAppdata() && !(appdatareads % 2 == 0)) {
138         // byte[] cappd = appd.getClientAppdata();
139         // if (cappd!=null)
140         // System.out.println("Client appdata\n"+cappd.toString()+"\nEnd of
141         // Appdata\n");
142         System.out.println("Testing read from inputstream");
143         String cappds = readData(appd.getClientInputStream());
144         System.out.println("Client appdata\n" + cappds + "\nEnd of Appdata\n");
145       } else {
146         if (!writtenonce) {
147           writtenonce = true;
148           // appd.setClientAppdata(makeappData("Client Appdata for
149           // "+user.toString()+" written"));
150           writeData(appd.getClientOutputStream(),
151               "Client Appdata for all users written on " + appdatareads
152                   + " read by " + vorbaclient.getUserHandle());
153           System.out.println("Written to ClientAppdata stream.");
154         }
155       }
156       if (appd.hasUserAppdata() && !(appdatareads % 2 == 0)) {
157         byte[] cappd = appd.getUserAppdata();
158         if (cappd != null)
159           System.out.println("User appdata\n" + new String(cappd)
160               + "\nEnd of Users' Appdata\n");
161         else {
162           System.out.println("No user appdata.");
163           appd.setUserAppdata(("no default - overwritten null byte set on "
164               + appdatareads + " read by " + vorbaclient.getUserHandle() + "")
165               .getBytes());
166         }
167       } else if (!writtenonce) {
168         writtenonce = true;
169         byte[] bts = makeappData("User Appdata for " + user + " written on "
170             + appdatareads + " read at ");
171         System.out.println("Setting appData bytes to\n" + new String(bts)
172             + "\nEnd.");
173         appd.setUserAppdata(bts);
174         System.out.println("Written to UserAppdata stream.");
175       }
176     }
177   }
178
179   private byte[] makeappData(String message) {
180     StringBuffer sb = new StringBuffer();
181     sb.append(message);
182     sb.append("on " + new java.util.Date());
183     return sb.toString().getBytes();
184   }
185
186   private boolean writeData(AppDataOutputStream os, String message) {
187     StringBuffer sb = new StringBuffer();
188     sb.append(message);
189     sb.append("on " + new java.util.Date());
190     try {
191       ObjectOutputStream oos = new ObjectOutputStream(os);
192       oos.writeObject(sb.toString());
193       oos.flush();
194       oos.close();
195     } catch (Exception e) {
196       System.err.println("Problem serialising this message:\n" + sb);
197       e.printStackTrace(System.err);
198       return false;
199     }
200     return true;
201   }
202
203   private String readData(AppDataInputStream is) {
204     if (is != null) {
205       try {
206         if (is.available() > 0) {
207           ObjectInputStream ois = new ObjectInputStream(is);
208           String rs = (String) ois.readObject();
209           return rs;
210         }
211       } catch (Exception e) {
212         System.err.println("Failed to read a string from input stream!");
213         e.printStackTrace(System.err);
214       }
215     }
216     return "";
217   }
218
219   private void addHandlers(IClient avorbaclient) {
220     final ExampleApplication me = this;
221     // make a non-volatile reference to the client instance.
222     final IClient vorbaclient = avorbaclient;
223     // register update handler
224     vorbaclient.addDocumentUpdateHandler(new PropertyChangeListener() {
225       public void propertyChange(PropertyChangeEvent evt) {
226         System.out.println("Vamsas document update for "
227             + evt.getPropertyName() + ": " + evt.getOldValue() + " to "
228             + evt.getNewValue());
229         // merge new data into ours.
230         // example - output doc
231         try {
232           IClientDocument cdoc = vorbaclient.getClientDocument();
233           if (calls > 2 && cdoc.getVamsasRoots().length > 0
234               && !cdoc.getVamsasRoots()[0].is__stored_in_document()) {
235             System.err
236                 .println("Pathological Update Detected - Document is zeroed!");
237           }
238           calls++;
239           uk.ac.vamsas.test.simpleclient.ArchiveReports.rootReport(cdoc
240               .getVamsasRoots(), true, System.out);
241           // Simple update
242           try {
243             if (cdoc.getVamsasRoots().length > 2) {
244               uk.ac.vamsas.objects.core.DataSet ds = cdoc.getVamsasRoots()[1]
245                   .getDataSet(0);
246               uk.ac.vamsas.objects.core.AlignmentSequence alsq = ds
247                   .getAlignment(0).getAlignmentSequence(0);
248               if (alsq.isUpdated())
249                 System.out.println("Seqeuence was updated since last time.");
250               alsq.setSequence(alsq.getSequence()
251                   + ds.getAlignment(0).getGapChar());
252               System.out.println("Newly Modified Sequence:\n"
253                   + alsq.getSequence());
254               cdoc.setVamsasRoots(cdoc.getVamsasRoots());
255             }
256           } catch (Exception ee) {
257             System.err.println("Exception whilst updating :");
258             ee.printStackTrace(System.err);
259           }
260           vorbaclient.updateDocument(cdoc);
261         } catch (Exception e) {
262           System.err
263               .println("Exception whilst dumping document tree after an update.");
264           e.printStackTrace(System.err);
265         }
266         isUpdated = true; // tell main thread to reflect change...
267       }
268     });
269     // register close handler
270     vorbaclient.addVorbaEventHandler(Events.DOCUMENT_REQUESTTOCLOSE,
271         new PropertyChangeListener() {
272           public void propertyChange(PropertyChangeEvent evt) {
273             System.out.println("Received request to close vamsas document.");
274             // ask user for a filename to save it to.
275             // Then pass it to the vorba object...
276             vorbaclient.storeDocument(new java.io.File("UserLocation"));
277           }
278         });
279
280     // register some more handlers to monitor the session :
281
282     vorbaclient.addVorbaEventHandler(Events.CLIENT_CREATION,
283         new PropertyChangeListener() {
284           public void propertyChange(PropertyChangeEvent evt) {
285             System.out.println("New Vamsas client for " + evt.getPropertyName()
286                 + ": " + evt.getOldValue() + " to " + evt.getNewValue());
287             // tell app add new client to its list of clients.
288           }
289         });
290     vorbaclient.addVorbaEventHandler(Events.CLIENT_FINALIZATION,
291         new PropertyChangeListener() {
292           public void propertyChange(PropertyChangeEvent evt) {
293             System.out.println("Vamsas client finalizing for "
294                 + evt.getPropertyName() + ": " + evt.getOldValue() + " to "
295                 + evt.getNewValue());
296             // tell app to update its list of clients to communicate
297             // with.
298           }
299         });
300     vorbaclient.addVorbaEventHandler(Events.SESSION_SHUTDOWN,
301         new PropertyChangeListener() {
302           public void propertyChange(PropertyChangeEvent evt) {
303             System.out.println("Session " + evt.getPropertyName()
304                 + " is shutting down.");
305             // tell app to finalize its session data before
306             // shutdown.
307           }
308         });
309     vorbaclient.addVorbaEventHandler(Events.DOCUMENT_FINALIZEAPPDATA,
310         new PropertyChangeListener() {
311           public void propertyChange(PropertyChangeEvent evt) {
312             boolean finalized = false;
313             System.out
314                 .println("Application received a DOCUMENT_FINALIZEAPPDATA event.");
315             IClientDocument cdoc = null;
316             try {
317               cdoc = vorbaclient.getClientDocument();
318               if (cdoc != null) {
319                 IClientAppdata apd = cdoc.getClientAppdata();
320                 if (apd != null) {
321                   String userd = "";
322                   if (apd.getUserAppdata()!=null)
323                     {
324                       userd = new String(apd.getUserAppdata());
325                     }
326                   String appdat = me.readData(apd.getClientInputStream());
327                   me.writeData(apd.getClientOutputStream(), appdat
328                       + "\nUser Data merged\n" + userd + "\n");
329                 }
330                 finalized = true;
331                 vorbaclient.updateDocument(cdoc);
332               }
333               // tell app to finalize its session data prior to the
334               // storage of the current session as an archive.
335             } catch (Exception e) {
336               if (!finalized) {
337                 System.err
338                     .println("Probable library problem - exception when trying to update document after writing merged appdata.");
339                 e.printStackTrace(System.err);
340               } else {
341                 System.err
342                     .println("Recovering from exception when writing merged appdata");
343                 e.printStackTrace(System.err);
344                 try {
345                   if (cdoc != null) {
346                     vorbaclient.updateDocument(cdoc);
347                   }
348                 } catch (Exception e2) {
349                   System.err
350                       .println("Probable library problem - exception when trying to update document after an exception when writing merged appdata.");
351                   e2.printStackTrace(System.err);
352                 }
353               }
354               return;
355             }
356             System.out.println("Application finalized appdata successfuly.");
357           }
358
359         });
360   }
361
362   public String Usage = "ExampleApplication :/n [-arena <vamsasFileDirectory>][-session <vamsasSessionURN>] <action> [+<arguments>]\n"
363       + "<action> is one of :\n\tsave,update,close,watch";
364
365   String sess = null;
366
367   String importFile = null;
368
369   String outputFile = null;
370
371   private boolean parseArgs(String args[]) {
372     if (args.length == 0) {
373       return false;
374     }
375     int cpos = 0;
376     boolean parsed = false;
377     while (!parsed && cpos < args.length) {
378       if (args[cpos].toLowerCase().equals("load") && cpos + 1 < args.length) {
379         importFile = args[cpos + 1];
380         cpos += 2;
381         continue;
382       }
383       if (args[cpos].toLowerCase().equals("save") && cpos + 1 < args.length) {
384         outputFile = args[cpos + 1];
385         cpos += 2;
386         continue;
387       }
388       // default behaviour - if not anything else its probably a session urn
389       if (!args[cpos].toLowerCase().equals("watch")) {
390         sess = args[cpos];
391       }
392       cpos++;
393     }
394     return true;
395   }
396
397   class ExamplePicker extends Thread {
398     String me = null;
399
400     public IPickManager pm = null;
401
402     ExamplePicker(String me, IPickManager pm) {
403       this.me = me;
404       this.pm = pm;
405     }
406
407     public void run() {
408       int mcount = 1;
409       while (pm != null) {
410         try {
411           Thread.sleep(1000 + (long) Math.random() * 10000);
412         } catch (Exception e) {
413         }
414
415         if (pm != null) {
416           pm.sendMessage(new uk.ac.vamsas.client.picking.CustomMessage(
417               "Message " + mcount++ + " from " + me));
418         }
419       }
420     }
421
422   }
423
424   long shutdown = -1;
425
426   public void runMe(String[] args) {
427     if (!parseArgs(args)) {
428       System.err.print(Usage);
429     }
430     // get IClientFactory
431     try {
432       clientfactory = new uk.ac.vamsas.client.simpleclient.SimpleClientFactory();
433     } catch (IOException e) {
434       System.err.println(e + "\n" + Usage);
435       System.exit(1);
436     }
437
438     // get an Iclient with session data
439     app = new ClientHandle("uk.ac.vamsas.test.ExampleApplication", "0.1");
440     user = new UserHandle("arnolduser", "deathsdoor");
441     try {
442       if (sess != null) {
443         System.out.println("Connecting to " + sess);
444         vorbaclient = clientfactory.getIClient(app, user, sess);
445       } else {
446         vorbaclient = clientfactory.getIClient(app, user);
447       }
448     } catch (NoDefaultSessionException e) {
449       System.err
450           .println("There appear to be several sessions to choose from :");
451       String[] sessions = clientfactory.getCurrentSessions();
452       for (int s = 0; s < sessions.length; s++)
453         System.err.println(sessions[s]);
454       System.exit(2);
455     }
456     addHandlers(vorbaclient);
457     try {
458       vorbaclient.joinSession();
459     } catch (Exception se) {
460       se.printStackTrace();
461       System.err.println(se + " when joining session.\n" + Usage);
462       System.exit(1);
463     }
464     // register an update listener and a close listener.
465     // import any data if requested to
466     if (importFile != null) {
467       File vfile = new File(importFile);
468       try {
469         vorbaclient.importDocument(vfile);
470       } catch (Exception e) {
471         System.err.println("Failed to import file " + importFile);
472         System.err.println("Exception received was " + e);
473         e.printStackTrace(System.err);
474       }
475
476     }
477     // Write out any data if requested to
478     if (outputFile != null) {
479       File vfile = new File(outputFile);
480       try {
481         vorbaclient.storeDocument(vfile);
482       } catch (Exception e) {
483         System.err.println("Failed to export session as file " + outputFile);
484         System.err.println("Exception received was " + e);
485         e.printStackTrace(System.err);
486       }
487     }
488     // get document data
489     try {
490       IClientDocument cdoc = vorbaclient.getClientDocument();
491       processVamsasDocument(cdoc);
492     } catch (Exception e) {
493       System.err
494           .println("Unexpected exception when retrieving the client document for the first time!");
495       e.printStackTrace(System.err);
496       System.exit(1);
497     }
498     int update = 0;
499     ExamplePicker picker = new ExamplePicker(vorbaclient.getClientHandle()
500         .getClientUrn(), vorbaclient.getPickManager());
501
502     picker.start();
503     if (picker.pm != null) {
504       picker.pm.registerMessageHandler(new IMessageHandler() {
505
506         public void handleMessage(Message message) {
507           System.out.println("Received |" + message.getRawMessage() + "|");
508           shutdown += 100; // hang around for 5 seconds or so before dying
509           // naturally.
510
511         }
512
513       });
514     }
515     shutdown = System.currentTimeMillis() + 10000; // hang around for 10
516     // seconds or so before
517     // dying naturally.
518     while (!isShuttingdown && update < totalUpdates) {
519       // do something with data
520       // , update document, or something.
521       // ..
522       if (isUpdated) {
523         System.out.println("Update handler called " + (++update) + " times");
524         System.out.println("******************************************");
525         isUpdated = false; // TODO: saner update det method.
526         shutdown = System.currentTimeMillis() + 10000;
527         if (update % 2 == 1) {
528           try {
529             IClientDocument cdoc = vorbaclient.getClientDocument();
530             processVamsasDocument(cdoc);
531           } catch (Exception e) {
532             System.err
533                 .println("Error when updating document after an even numbered update.");
534             e.printStackTrace(System.err);
535           }
536         }
537       } else {
538         if (System.currentTimeMillis() > shutdown) {
539           isShuttingdown = true;
540         }
541       }
542
543       try {
544         Thread.sleep(50);
545       } catch (Exception e) {
546       }
547
548     }
549     System.out.println("Finalizing.");
550     // call finalizeClient
551     vorbaclient.finalizeClient();
552     System.out.println("Shutting down picker.");
553     picker.pm = null;
554     while (picker.isAlive()) {
555       System.out.println("Waiting for picker to die...");
556       try {
557         Thread.sleep(1000);
558       } catch (Exception e) {
559       }
560       ;
561     }
562
563     // { meanwhile, eventHandlers are called to do any saves if need be }
564     // and all registered listeners will be deregistered to avoid deadlock.
565
566     // finish
567     vorbaclient=null;
568     clientfactory=null;
569     System.out.println("Byee!");
570   }
571
572   public static void main(String[] args) {
573     ExampleApplication example = new ExampleApplication();
574     example.runMe(args);
575   }
576 }