3722109b2a0c3cb467a4ce626dbac53a8e181424
[vamsas.git] / src / uk / ac / vamsas / test / ExampleApplication.java
1 /**
2  * Created on 14-Sep-2005
3  *
4  * TODO To change the template for this generated file go to
5  * Window - Preferences - Java - Code Style - Code Templates
6  */
7 package uk.ac.vamsas.test;
8
9 import uk.ac.vamsas.client.*;
10 import uk.ac.vamsas.client.picking.IMessageHandler;
11 import uk.ac.vamsas.client.picking.IPickManager;
12 import uk.ac.vamsas.client.picking.Message;
13 import uk.ac.vamsas.objects.core.VAMSAS;
14 import uk.ac.vamsas.test.objects.Core;
15
16 import java.awt.Event;
17 import java.beans.PropertyChangeEvent;
18 import java.beans.PropertyChangeListener;
19 import java.io.IOException;
20 import java.util.Vector;
21
22 /**
23  * Toy vamsas command line client application demonstrating the API. TODO: test
24  * appData get/set methods TODO: verify and test pickManager and interaction
25  * between it and other session events TODO: add more session interaction events
26  * (currently: modifies document on start up, then modifies every 2 updates
27  * before finalizing after 5 updates.
28  * 
29  * @author jimp
30  */
31
32 public class ExampleApplication
33 {
34   private static ClientHandle app;
35
36   private static UserHandle user; // TODO: make this something defined by the
37   // api
38
39   private static IClientFactory clientfactory;
40
41   private static IClient vorbaclient;
42
43   private static byte[] mydata;
44
45   private static Vector vamsasObjects;
46
47   private static boolean isUpdated = false;
48
49   private static boolean isShuttingdown = false;
50
51   private static boolean isFinalizing = false;
52
53   private static void processVamsasDocument(IClientDocument doc)
54   {
55     doc.addVamsasRoot(Core.getDemoVamsas());
56     vorbaclient.updateDocument(doc);
57     // merge vamsasObjects with vamsas objects in document
58     // get this apps 'mydata' if it hasn't got it already.
59     // .. access this application's 'public' mydata' if there is any.
60   }
61
62   private static void addHandlers(IClient avorbaclient)
63   {
64     // make a non-volatile reference to the client instance.
65     final IClient vorbaclient = avorbaclient;
66     // register update handler
67     vorbaclient.addDocumentUpdateHandler(new PropertyChangeListener() {
68       public void propertyChange(PropertyChangeEvent evt)
69       {
70         System.out.println("Vamsas document update for "
71             + evt.getPropertyName() + ": " + evt.getOldValue()
72             + " to " + evt.getNewValue());
73         // merge new data into ours.
74         // example - output doc
75         try
76         {
77           IClientDocument cdoc = vorbaclient.getClientDocument();
78           uk.ac.vamsas.test.simpleclient.ArchiveReports.rootReport(
79               cdoc.getVamsasRoots(), true, System.out);
80           vorbaclient.updateDocument(cdoc);
81         }
82         catch (Exception e)
83         {
84           System.err
85           .println("Exception whilst dumping document tree after an update.");
86           e.printStackTrace(System.err);
87         }
88         isUpdated = true; // tell main thread to reflect change...
89       }
90     });
91     // register close handler
92     vorbaclient.addVorbaEventHandler(Events.DOCUMENT_REQUESTTOCLOSE,
93         new PropertyChangeListener() {
94       public void propertyChange(PropertyChangeEvent evt)
95       {
96         System.out
97         .println("Received request to close vamsas document.");
98         // ask user for a filename to save it to.
99         // Then pass it to the vorba object...
100         vorbaclient.storeDocument(new java.io.File(
101         "UserLocation"));
102       }
103     });
104
105     // register some more handlers to monitor the session :
106
107     vorbaclient.addVorbaEventHandler(Events.CLIENT_CREATION,
108         new PropertyChangeListener() {
109       public void propertyChange(PropertyChangeEvent evt)
110       {
111         System.out.println("New Vamsas client for "
112             + evt.getPropertyName() + ": "
113             + evt.getOldValue() + " to "
114             + evt.getNewValue());
115         // tell app add new client to its list of clients.
116       }
117     });
118     vorbaclient.addVorbaEventHandler(Events.CLIENT_FINALIZATION,
119         new PropertyChangeListener() {
120       public void propertyChange(PropertyChangeEvent evt)
121       {
122         System.out.println("Vamsas client finalizing for "
123             + evt.getPropertyName() + ": "
124             + evt.getOldValue() + " to "
125             + evt.getNewValue());
126         // tell app to update its list of clients to communicate
127         // with.
128       }
129     });
130     vorbaclient.addVorbaEventHandler(Events.SESSION_SHUTDOWN,
131         new PropertyChangeListener() {
132       public void propertyChange(PropertyChangeEvent evt)
133       {
134         System.out.println("Session " + evt.getPropertyName()
135             + " is shutting down.");
136         // tell app to finalize its session data before
137         // shutdown.
138       }
139     });
140     vorbaclient.addVorbaEventHandler(Events.DOCUMENT_FINALIZEAPPDATA,
141         new PropertyChangeListener() {
142       public void propertyChange(PropertyChangeEvent evt)
143       {
144         System.out
145         .println("Application received a DOCUMENT_FINALIZEAPPDATA event.");
146         // tell app to finalize its session data prior to the
147         // storage of the current session as an archive.
148       }
149     });
150
151   }
152
153   public static String Usage = "ExampleApplication [session urn] watch/n( future usage is :/n <vamsasFileDirectory> <vamsasSessionURN> <action> [+<arguments>]\n"
154     + "<action> is one of :\n\tsave,update,close,watch";
155
156   static String sess = null;
157
158   private static boolean parseArgs(String args[])
159   {
160     if (args.length == 0)
161     {
162       return false;
163     }
164     if (!args[0].toLowerCase().equals("watch"))
165     {
166       sess = args[0];
167     }
168     return true;
169   }
170
171   public static void main(String[] args)
172   {
173     class ExamplePicker extends Thread
174     {
175       String me = null;
176
177       public IPickManager pm = null;
178
179       ExamplePicker(String me, IPickManager pm)
180       {
181         this.me = me;
182         this.pm = pm;
183       }
184
185       public void run()
186       {
187         int mcount = 1;
188         while (pm != null)
189         {
190           try { Thread.sleep(1000 + (long) Math.random() * 10000); }
191           catch (Exception e) {}
192
193           if (pm != null)
194           {
195             pm.sendMessage(new uk.ac.vamsas.client.picking.CustomMessage("Message " + mcount++ + " from " + me));
196           }
197         }
198       }
199
200     }
201
202     if (!parseArgs(args))
203     {
204       System.err.print(Usage);
205     }
206     // get IClientFactory
207     try
208     {
209       clientfactory = new uk.ac.vamsas.client.simpleclient.SimpleClientFactory();
210     }
211     catch (IOException e)
212     {
213       System.err.println(e + "\n" + Usage);
214       System.exit(1);
215     }
216
217     // get an Iclient with session data
218     app = new ClientHandle("uk.ac.vamsas.test.ExampleApplication", "0.1");
219     user = new UserHandle("arnolduser", "deathsdoor");
220     try
221     {
222       vorbaclient = clientfactory.getIClient(app, user);
223     }
224     catch (NoDefaultSessionException e)
225     {
226       System.err
227       .println("There appear to be several sessions to choose from :");
228       String[] sessions = clientfactory.getCurrentSessions();
229       for (int s = 0; s < sessions.length; s++)
230         System.err.println(sessions[s]);
231       System.exit(2);
232     }
233     addHandlers(vorbaclient);
234     try
235     {
236       vorbaclient.joinSession();
237     }
238     catch (Exception se)
239     {
240       se.printStackTrace();
241       System.err.println(se + " when joining session.\n" + Usage);
242       System.exit(1);
243     }
244     // register an update listener and a close listener.
245     // get document data
246     try
247     {
248       IClientDocument cdoc = vorbaclient.getClientDocument();
249       processVamsasDocument(cdoc);
250     }
251     catch (Exception e)
252     {
253       System.err
254       .println("Unexpected exception when retrieving the client document for the first time!");
255       e.printStackTrace(System.err);
256       System.exit(1);
257     }
258     int update = 0;
259     ExamplePicker picker = new ExamplePicker(vorbaclient.getClientHandle()
260         .getClientUrn(), vorbaclient.getPickManager());
261
262     picker.start();
263     if (picker.pm!=null) {
264       picker.pm.registerMessageHandler(new IMessageHandler() {
265
266         public void handleMessage(Message message)
267         {
268           System.out
269           .println("Received |" + message.getRawMessage() + "|");
270         }
271
272       });
273     }
274     while (!isShuttingdown && update < 5)
275     {
276       // do something with data
277       // , update document, or something.
278       // ..
279       if (isUpdated)
280       {
281         System.out.println("Update handler called " + (++update)
282             + " times");
283         System.out
284         .println("******************************************");
285         isUpdated = false; // TODO: saner update det method.
286         if (update % 2 == 1)
287         {
288           try
289           {
290             IClientDocument cdoc = vorbaclient.getClientDocument();
291             processVamsasDocument(cdoc);
292           }
293           catch (Exception e)
294           {
295             System.err
296             .println("Error when updating document after an even numbered update.");
297             e.printStackTrace(System.err);
298           }
299         }
300       }
301
302       try       { Thread.sleep(15); }
303       catch (Exception e) {}
304
305     }
306     System.out.println("Finalizing.");
307     // call finalizeClient
308     vorbaclient.finalizeClient();
309     System.out.println("Shutting down picker.");
310     picker.pm = null;
311     while (picker.isAlive())
312     {
313       System.out.println("Waiting for picker to die...");
314       try
315       {
316         Thread.sleep(1000);
317       }
318       catch (Exception e)
319       {
320       }
321       ;
322     }
323
324     // { meanwhile, eventHandlers are called to do any saves if need be }
325     // and all registered listeners will be deregistered to avoid deadlock.
326
327     // finish
328     System.out.println("Byee!");
329   }
330
331 }