328495b6796498c7a34d6167cd7946e62774b8a9
[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  * Toy vamsas command line client application demonstrating the API.
23  * TODO: test appData get/set methods
24  * TODO: verify and test pickManager and interaction between it and other session events
25  * TODO: add more session interaction events (currently: modifies document on start up, then modifies every 2 updates before finalizing after 5 updates.
26  * @author jimp
27  */
28
29 public class ExampleApplication {
30   private static ClientHandle app;
31   private static UserHandle user; // TODO: make this something defined by the api
32   private static IClientFactory clientfactory;
33   private static IClient vorbaclient;
34   private static byte[] mydata;
35   private static Vector vamsasObjects;
36   private static boolean isUpdated = false;
37   private static boolean isShuttingdown = false;
38   private static boolean isFinalizing = false;
39   private static void processVamsasDocument(IClientDocument doc) {
40     doc.addVamsasRoot(Core.getDemoVamsas());
41     vorbaclient.updateDocument(doc);
42     // merge vamsasObjects with vamsas objects in document
43     // get this apps 'mydata' if it hasn't got it already.
44     // .. access this application's 'public' mydata' if there is any.
45   }
46   private static void addHandlers(IClient avorbaclient) {
47     // make a non-volatile reference to the client instance.
48     final IClient vorbaclient = avorbaclient;
49     // register update handler
50     vorbaclient.addDocumentUpdateHandler(new PropertyChangeListener() {
51       public void propertyChange(PropertyChangeEvent evt) {
52         System.out.println("Vamsas document update for "+evt.getPropertyName()
53             +": "+evt.getOldValue()+" to "+evt.getNewValue());
54         // merge new data into ours.
55         // example - output doc
56         try {
57           IClientDocument cdoc = vorbaclient.getClientDocument();
58           uk.ac.vamsas.test.simpleclient.ArchiveReports.rootReport(cdoc.getVamsasRoots(), true, System.out);
59           vorbaclient.updateDocument(cdoc);
60         } catch (Exception e) {
61           System.err.println("Exception whilst dumping document tree after an update.");
62           e.printStackTrace(System.err);
63         }
64         isUpdated=true; // tell main thread to reflect change...
65       }
66     });
67     // register close handler
68     vorbaclient.addVorbaEventHandler(Events.DOCUMENT_REQUESTTOCLOSE, 
69         new PropertyChangeListener() {
70         public void propertyChange(PropertyChangeEvent evt) {
71           System.out.println("Received request to close vamsas document.");
72           // ask user for a filename to save it to. 
73           // Then pass it to the vorba object...
74           vorbaclient.storeDocument(new java.io.File("UserLocation"));
75         }
76     });
77     
78     // register some more handlers to monitor the session :
79     
80     vorbaclient.addVorbaEventHandler(Events.CLIENT_CREATION, 
81         new PropertyChangeListener() {
82       public void propertyChange(PropertyChangeEvent evt) {
83         System.out.println("New Vamsas client for "+evt.getPropertyName()
84             +": "+evt.getOldValue()+" to "+evt.getNewValue());
85         // tell app add new client to its list of clients.
86       }
87     });
88     vorbaclient.addVorbaEventHandler(Events.CLIENT_FINALIZATION, 
89         new PropertyChangeListener() {
90       public void propertyChange(PropertyChangeEvent evt) {
91         System.out.println("Vamsas client finalizing for "+evt.getPropertyName()
92             +": "+evt.getOldValue()+" to "+evt.getNewValue());
93         // tell app to update its list of clients to communicate with.
94       }
95     });
96     vorbaclient.addVorbaEventHandler(Events.SESSION_SHUTDOWN, 
97         new PropertyChangeListener() {
98       public void propertyChange(PropertyChangeEvent evt) {
99         System.out.println("Session "+evt.getPropertyName()+" is shutting down.");
100         // tell app to finalize its session data before shutdown.
101       }
102     });
103     vorbaclient.addVorbaEventHandler(Events.DOCUMENT_FINALIZEAPPDATA, 
104         new PropertyChangeListener() {
105       public void propertyChange(PropertyChangeEvent evt) {
106         System.out.println("Application received a DOCUMENT_FINALIZEAPPDATA event.");
107         // tell app to finalize its session data prior to the storage of the current session as an archive.
108       }
109     });
110     
111   }
112   public static String 
113         Usage="ExampleApplication [session urn] watch/n( future usage is :/n <vamsasFileDirectory> <vamsasSessionURN> <action> [+<arguments>]\n"
114           +"<action> is one of :\n\tsave,update,close,watch";
115   static String sess=null;
116   private static boolean parseArgs(String args[]) {
117     if (args.length==0) {
118       return false;
119     }
120     if (!args[0].toLowerCase().equals("watch")) {
121       sess=args[0];
122     }
123     return true;
124   }
125   public static void main(String[] args) {
126     class ExamplePicker implements Runnable {
127       String me=null;
128       public IPickManager pm = null;
129       ExamplePicker(String me,IPickManager pm) {
130         this.me = me;
131         this.pm = pm;
132       }
133       public void run() {
134         int mcount=1;
135         while (pm!=null) {
136           try { Thread.sleep(1000+(long) Math.random()*10000); }
137           catch (Exception e){ };
138           if (pm!=null)
139           {
140             pm.sendMessage(new uk.ac.vamsas.client.picking.CustomMessage("Message "+mcount+++" from "+me));
141           }
142         }
143       }
144         
145     };
146
147     if (!parseArgs(args)) {
148       System.err.print(Usage);
149     }
150     // get IClientFactory
151     try {
152       clientfactory = new uk.ac.vamsas.client.simpleclient.SimpleClientFactory();
153     } catch (IOException e) {
154       System.err.println(e+"\n"+Usage);
155       System.exit(1);
156     }
157     
158     // get an Iclient with session data
159     app = new ClientHandle("uk.ac.vamsas.test.ExampleApplication","0.1");
160     user = new UserHandle("arnolduser","deathsdoor");
161     try {
162       vorbaclient = clientfactory.getIClient(app, user);
163     } catch (NoDefaultSessionException e) {
164       System.err.println("There appear to be several sessions to choose from :");
165       String[] sessions = clientfactory.getCurrentSessions();
166       for (int s=0;s<sessions.length; s++)
167         System.err.println(sessions[s]);
168       System.exit(2);
169     }
170     addHandlers(vorbaclient);
171     try {
172       vorbaclient.joinSession();
173     }
174     catch (Exception se) {
175       se.printStackTrace();
176       System.err.println(se+" when joining session.\n"+Usage);
177       System.exit(1);
178     }
179     // register an update listener and a close listener.
180     // get document data
181     try {
182       IClientDocument cdoc = vorbaclient.getClientDocument();
183       processVamsasDocument(cdoc);
184     } catch (Exception e) {
185       System.err.println("Unexpected exception when retrieving the client document for the first time!");
186       e.printStackTrace(System.err);
187       System.exit(1);
188     }
189     int update=0;
190     ExamplePicker picker = new ExamplePicker(vorbaclient.getClientHandle().getClientUrn(),vorbaclient.getPickManager());
191     Thread pickthread = new Thread(picker);
192     pickthread.start();
193     picker.pm.registerMessageHandler(new IMessageHandler() {
194
195       public void handleMessage(Message message) {
196         System.out.println("Received |"+message.getRawMessage()+"|");
197       }
198       
199     });
200     while (!isShuttingdown && update<5) {
201       // do something with data
202       // , update document, or something.
203       // ..
204       if (isUpdated) {
205         System.out.println("Update handler called "+(++update)+" times");
206         System.out.println("******************************************");
207         isUpdated=false; // TODO: saner update det method.
208         if (update % 2==1) {
209           try {
210             IClientDocument cdoc = vorbaclient.getClientDocument();
211             processVamsasDocument(cdoc);
212           }
213           catch (Exception e) {
214             System.err.println("Error when updating document after an even numbered update.");
215             e.printStackTrace(System.err);
216           }
217         }
218       }
219       try { Thread.sleep(15); } catch (Exception e) {};
220     }
221     System.out.println("Shutting down picker.");
222     picker.pm=null;
223     while (pickthread.isAlive()) {
224       System.out.println("Waiting for picker to die...");
225       try { Thread.sleep(1000); 
226       } catch (Exception e) {};
227     }
228   
229     System.out.println("Finalizing.");
230       // call finalizeClient
231     vorbaclient.finalizeClient();
232     // { meanwhile, eventHandlers are called to do any saves if need be }
233     // and all registered listeners will be deregistered to avoid deadlock.
234     
235     // finish
236   }
237   
238 }