1 package uk.ac.vamsas.test;
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;
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;
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;
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.
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.
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
45 * TODO: test appData get/set methods
47 * TODO: verify and test pickManager and interaction between it and other
50 * TODO: add more session interaction events
52 * TODO: test client add/leave events - currently library generates exceptions
53 * for sessionlist and clientlist modifications.
58 public class ExampleApplication {
59 private ClientHandle app;
61 private UserHandle user; // TODO: make this something defined by the
65 private IClientFactory clientfactory;
67 private IClient vorbaclient;
69 private byte[] mydata;
71 private Vector vamsasObjects;
73 private boolean isUpdated = false;
75 private boolean isShuttingdown = false;
77 private boolean isFinalizing = false;
79 private int totalUpdates = 9;
81 private uk.ac.vamsas.client.VorbaId recover = null;
83 private int calls = 0;
85 private long mdatahash = 0;
87 private long muserdatahash = 0;
89 private void processVamsasDocument(IClientDocument doc) {
90 if (doc.getVamsasRoots().length < 4) {
91 doc.addVamsasRoot(Core.getDemoVamsas());
94 uk.ac.vamsas.objects.core.DataSet ds = doc.getVamsasRoots()[1]
96 uk.ac.vamsas.objects.core.AlignmentSequence alsq = ds.getAlignment(0)
97 .getAlignmentSequence(0);
98 if (recover == null) {
99 recover = alsq.getVorbaId();
101 Vobject recoverd = doc.getObject(recover);
102 System.out.println("Recovery of " + recover + " was "
103 + ((recoverd == null) ? "A FAILURE" : "SUCCESSFUL"));
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) {
114 // get this apps 'mydata' if it hasn't got it already.
115 System.out.println("Trying to get appdata and modify it.....");
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);
124 // .. access this application's 'public' mydata' if there is any.
125 vorbaclient.updateDocument(doc);
126 // merge vamsasObjects with vamsas objects in document
130 private int appdatareads = 0;
132 private void processAppData(IClientDocument doc) throws Exception {
134 boolean writtenonce = false;
136 uk.ac.vamsas.client.IClientAppdata appd = doc.getClientAppdata();
137 if (appd.hasClientAppdata() && !(appdatareads % 2 == 0)) {
138 // byte[] cappd = appd.getClientAppdata();
140 // System.out.println("Client appdata\n"+cappd.toString()+"\nEnd of
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");
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.");
156 if (appd.hasUserAppdata() && !(appdatareads % 2 == 0)) {
157 byte[] cappd = appd.getUserAppdata();
159 System.out.println("User appdata\n" + new String(cappd)
160 + "\nEnd of Users' Appdata\n");
162 System.out.println("No user appdata.");
163 appd.setUserAppdata(("no default - overwritten null byte set on "
164 + appdatareads + " read by " + vorbaclient.getUserHandle() + "")
167 } else if (!writtenonce) {
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)
173 appd.setUserAppdata(bts);
174 System.out.println("Written to UserAppdata stream.");
179 private byte[] makeappData(String message) {
180 StringBuffer sb = new StringBuffer();
182 sb.append("on " + new java.util.Date());
183 return sb.toString().getBytes();
186 private boolean writeData(AppDataOutputStream os, String message) {
187 StringBuffer sb = new StringBuffer();
189 sb.append("on " + new java.util.Date());
191 ObjectOutputStream oos = new ObjectOutputStream(os);
192 oos.writeObject(sb.toString());
195 } catch (Exception e) {
196 System.err.println("Problem serialising this message:\n" + sb);
197 e.printStackTrace(System.err);
203 private String readData(AppDataInputStream is) {
206 if (is.available() > 0) {
207 ObjectInputStream ois = new ObjectInputStream(is);
208 String rs = (String) ois.readObject();
211 } catch (Exception e) {
212 System.err.println("Failed to read a string from input stream!");
213 e.printStackTrace(System.err);
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
232 IClientDocument cdoc = vorbaclient.getClientDocument();
233 if (calls > 2 && cdoc.getVamsasRoots().length > 0
234 && !cdoc.getVamsasRoots()[0].is__stored_in_document()) {
236 .println("Pathological Update Detected - Document is zeroed!");
239 uk.ac.vamsas.test.simpleclient.ArchiveReports.rootReport(cdoc
240 .getVamsasRoots(), true, System.out);
243 if (cdoc.getVamsasRoots().length > 2) {
244 uk.ac.vamsas.objects.core.DataSet ds = cdoc.getVamsasRoots()[1]
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());
256 } catch (Exception ee) {
257 System.err.println("Exception whilst updating :");
258 ee.printStackTrace(System.err);
260 vorbaclient.updateDocument(cdoc);
261 } catch (Exception e) {
263 .println("Exception whilst dumping document tree after an update.");
264 e.printStackTrace(System.err);
266 isUpdated = true; // tell main thread to reflect change...
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"));
280 // register some more handlers to monitor the session :
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.
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
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
309 vorbaclient.addVorbaEventHandler(Events.DOCUMENT_FINALIZEAPPDATA,
310 new PropertyChangeListener() {
311 public void propertyChange(PropertyChangeEvent evt) {
312 boolean finalized = false;
314 .println("Application received a DOCUMENT_FINALIZEAPPDATA event.");
315 IClientDocument cdoc = null;
317 cdoc = vorbaclient.getClientDocument();
319 IClientAppdata apd = cdoc.getClientAppdata();
322 if (apd.getUserAppdata()!=null)
324 userd = new String(apd.getUserAppdata());
326 String appdat = me.readData(apd.getClientInputStream());
327 me.writeData(apd.getClientOutputStream(), appdat
328 + "\nUser Data merged\n" + userd + "\n");
331 vorbaclient.updateDocument(cdoc);
333 // tell app to finalize its session data prior to the
334 // storage of the current session as an archive.
335 } catch (Exception e) {
338 .println("Probable library problem - exception when trying to update document after writing merged appdata.");
339 e.printStackTrace(System.err);
342 .println("Recovering from exception when writing merged appdata");
343 e.printStackTrace(System.err);
346 vorbaclient.updateDocument(cdoc);
348 } catch (Exception e2) {
350 .println("Probable library problem - exception when trying to update document after an exception when writing merged appdata.");
351 e2.printStackTrace(System.err);
356 System.out.println("Application finalized appdata successfuly.");
362 public String Usage = "ExampleApplication :/n [-arena <vamsasFileDirectory>][-session <vamsasSessionURN>] <action> [+<arguments>]\n"
363 + "<action> is one of :\n\tsave,update,close,watch";
367 String importFile = null;
369 String outputFile = null;
371 private boolean parseArgs(String args[]) {
372 if (args.length == 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];
383 if (args[cpos].toLowerCase().equals("save") && cpos + 1 < args.length) {
384 outputFile = args[cpos + 1];
388 // default behaviour - if not anything else its probably a session urn
389 if (!args[cpos].toLowerCase().equals("watch")) {
397 class ExamplePicker extends Thread {
400 public IPickManager pm = null;
402 ExamplePicker(String me, IPickManager pm) {
411 Thread.sleep(1000 + (long) Math.random() * 10000);
412 } catch (Exception e) {
416 pm.sendMessage(new uk.ac.vamsas.client.picking.CustomMessage(
417 "Message " + mcount++ + " from " + me));
426 public void runMe(String[] args) {
427 if (!parseArgs(args)) {
428 System.err.print(Usage);
430 // get IClientFactory
432 clientfactory = new uk.ac.vamsas.client.simpleclient.SimpleClientFactory();
433 } catch (IOException e) {
434 System.err.println(e + "\n" + Usage);
438 // get an Iclient with session data
439 app = new ClientHandle("uk.ac.vamsas.test.ExampleApplication", "0.1");
440 user = new UserHandle("arnolduser", "deathsdoor");
443 System.out.println("Connecting to " + sess);
444 vorbaclient = clientfactory.getIClient(app, user, sess);
446 vorbaclient = clientfactory.getIClient(app, user);
448 } catch (NoDefaultSessionException e) {
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]);
456 addHandlers(vorbaclient);
458 vorbaclient.joinSession();
459 } catch (Exception se) {
460 se.printStackTrace();
461 System.err.println(se + " when joining session.\n" + Usage);
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);
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);
477 // Write out any data if requested to
478 if (outputFile != null) {
479 File vfile = new File(outputFile);
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);
490 IClientDocument cdoc = vorbaclient.getClientDocument();
491 processVamsasDocument(cdoc);
492 } catch (Exception e) {
494 .println("Unexpected exception when retrieving the client document for the first time!");
495 e.printStackTrace(System.err);
499 ExamplePicker picker = new ExamplePicker(vorbaclient.getClientHandle()
500 .getClientUrn(), vorbaclient.getPickManager());
503 if (picker.pm != null) {
504 picker.pm.registerMessageHandler(new IMessageHandler() {
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
515 shutdown = System.currentTimeMillis() + 10000; // hang around for 10
516 // seconds or so before
518 while (!isShuttingdown && update < totalUpdates) {
519 // do something with data
520 // , update document, or something.
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) {
529 IClientDocument cdoc = vorbaclient.getClientDocument();
530 processVamsasDocument(cdoc);
531 } catch (Exception e) {
533 .println("Error when updating document after an even numbered update.");
534 e.printStackTrace(System.err);
538 if (System.currentTimeMillis() > shutdown) {
539 isShuttingdown = true;
545 } catch (Exception e) {
549 System.out.println("Finalizing.");
550 // call finalizeClient
551 vorbaclient.finalizeClient();
552 System.out.println("Shutting down picker.");
554 while (picker.isAlive()) {
555 System.out.println("Waiting for picker to die...");
558 } catch (Exception e) {
563 // { meanwhile, eventHandlers are called to do any saves if need be }
564 // and all registered listeners will be deregistered to avoid deadlock.
569 System.out.println("Byee!");
572 public static void main(String[] args) {
573 ExampleApplication example = new ExampleApplication();