598bfdd2996724a557ad218175ce13c4f0677d23
[vamsas.git] / src / org / vamsas / client / simpleclient / ClientsFile.java
1 package org.vamsas.client.simpleclient;
2
3 import org.vamsas.client.*;
4
5 import java.io.BufferedInputStream;
6 import java.io.BufferedOutputStream;
7 import java.io.File;
8 import java.io.FileInputStream;
9 import java.io.FileNotFoundException;
10 import java.io.FileOutputStream;
11 import java.io.IOException;
12 import java.io.InputStreamReader;
13 import java.io.ObjectInputStream;
14 import java.io.ObjectOutput;
15 import java.io.ObjectOutputStream;
16 import java.io.OutputStream;
17 import java.util.Vector;
18
19 /**
20  * Handler for the clientsFile within a vamsas session thread.
21  * @author jim 
22  */
23 public class ClientsFile extends ListFile {
24   /**
25    * number of my client in list - passed back when a client 
26    * is added to list, and used (if valid) for quickly 
27    * looking up presence of client handle in the list.
28    */
29   private int syncnum = 1;
30
31   public ClientsFile(File filelist) throws IOException {
32     super(filelist);
33   }
34
35   /**
36    * internal method for getting clientList - ensures a lock has been made but
37    * does not release it.
38    * 
39    * @return list of clients
40    */
41   private ClientHandle[] retrieveClientHandles() {
42     if (lockFile()) {
43       try {
44         ClientHandle[] clients=null;
45         if (this.fileLock.rafile.length()>0) {
46           ObjectInputStream is = new ObjectInputStream(new BufferedInputStream(
47               new java.io.FileInputStream(sessionFile)));
48           Object o;
49           o=is.readObject();
50           if (o!=null) {
51             try {
52               clients = (ClientHandle[]) o;
53             }
54             catch (Exception e) {
55               System.err.println("Garbage in the clientHandle list "+this.sessionFile);
56             }
57           }
58         }
59         return clients;
60       } catch (FileNotFoundException e) {
61         // TODO Auto-generated catch block
62         e.printStackTrace(System.err);
63       } catch (Exception e) {
64         e.printStackTrace(System.err);
65       }
66     }
67     return null;
68   }
69   /**
70    * get the clientList from the file. May return null if lock failed!
71    * @return clientList
72    */
73   public ClientHandle[] retrieveClientList() {
74     if (lockFile()) {
75       ClientHandle[] clients = retrieveClientHandles();
76       unlockFile();
77       return clients;
78     }
79     return null;
80   }
81   /**
82    * get list from the locked ClientList.
83    * @param extantlock
84    * @return clientList or null if lock failed (or file was empty)
85    */
86   public ClientHandle[] retrieveClientList(Lock extantlock) {
87     if (lockFile(extantlock)) {
88       ClientHandle[] clients = retrieveClientHandles();
89       unlockFile();
90       return clients;
91     }
92     return null;
93   }
94   /**
95    * adds clientHandle me to the clientList under an existing lock extantLock.
96    * @param me
97    * @param extantLock
98    * @return client index in list or 0 if lock was invalid or addClient operation failed.
99    */
100   public int addClient(ClientHandle me, Lock extantLock) {
101     return addClient(me, true, extantLock);
102   }
103   
104   /**
105    * adds clientHandle me to the clientList under an existing lock.
106    * @param me - clientHandle
107    * @param disambig - if true then add will fail if an identical clientHandle already exists
108    * @param extantLock - existing lock
109    * @return client index in list or 0 if addClient (or the lock) failed.
110    */
111   
112   public int addClient(ClientHandle me, boolean disambig, Lock extantLock) {
113     if (lockFile(extantLock)) {
114       syncnum = addClient(me, disambig);
115       unlockFile();
116       return syncnum;
117     }
118     return 0;
119   }
120   
121   /**
122    * adds the ClientHandle to the list - if it is not unique, then the
123    * ClientHandle object is modified to make it unique in the list. returns the
124    * clientNumber for the client in the session.
125    * 
126    * @param me
127    * @return
128    */
129
130   public int addClient(ClientHandle me) {
131     syncnum = addClient(me, true);
132     unlockFile();
133     return syncnum;
134   }
135
136   /**
137    * removes 'me' from the session ClientList without complaint if 'me' isn't in the clientList already.
138    * @param me client handle to be removed
139    * @param clientlock existing lock passed from watcher.
140    */
141   public void removeClient(ClientHandle me, Lock clientlock) {
142     int mynum=-1;
143     if (lockFile(clientlock)) {
144       ClientHandle[] clients = retrieveClientHandles();
145       if (clients != null) {
146         if ((syncnum<=0 || syncnum>clients.length) || clients[syncnum-1]!=me) {
147           for (int i = 0, j = clients.length; i < j; i++) 
148             if (clients[i].equals(me)) {
149               mynum=i;
150               break;
151             }
152         } else {
153           mynum=syncnum-1;
154         }
155         if (mynum>-1) {
156           ClientHandle[] newlist = new ClientHandle[clients.length - 1];
157           for (int k=0,i = 0, j = clients.length; i < j; i++)
158             if (i!=mynum)
159               newlist[k++] = clients[i];
160           if (!putClientList(newlist))
161             throw new Error("Failed to write new clientList!"); // failed to put the clientList to disk.
162         }
163       }
164       unlockFile();
165     } else {
166       throw new Error("Couldn't get lock for "+((sessionFile==null) ? "Unitialised sessionFile in ClientsFile" : sessionFile.getAbsolutePath()));
167     }
168   }
169   /**
170    * Adds a ClientHandle to the ClientList file - optionally disambiguating 
171    * the ClientHandle (modifes the URN). 
172    * Note: Caller is left to release the lock on the ClientList.
173    * @param me
174    * @param disambiguate -
175    *          flag indicating if the URN for me should be disambiguated to
176    *          differentiate between sessions.
177    * @return index of clientHandle in new list, or -1-position of existing
178    *         clientHandle (if disambiguate is true)
179    */
180   protected int addClient(ClientHandle me, boolean disambiguate) {
181     int newclient = 0;
182     if (lockFile()) {
183       ClientHandle[] clients = retrieveClientHandles();
184       if (me.getClientUrn()==null) {
185         // TODO: move this into ClientUrn as a standard form method.
186         me.setClientUrn("vamsas://"+me.getClientName()+":"+me.getVersion()+"/");
187       }
188       if (clients == null) {
189         clients = new ClientHandle[1];
190         clients[0] = me;
191         newclient = 1;
192       } else {
193         int k = 0;
194         for (int i = 0, j = clients.length; i < j; i++) {
195           if (clients[i].equals(me)) {
196             if (disambiguate) {
197               while (clients[i].equals(me)) {
198                 me.setClientUrn(me.getClientUrn() + k++); // TODO: make a better
199                                                           // disambiguation of
200                                                           // urn.
201               }
202             } else {
203               // will not write the ambiguous clientHandle to disk, just return
204               // its index.
205               return -1 - i;
206             }
207           }
208         }
209         int i, j;
210         ClientHandle[] newlist = new ClientHandle[clients.length + 1];
211         for (i = 0, j = clients.length; i < j; i++)
212           newlist[i] = clients[i];
213         newlist[j] = me;
214         clients = newlist;
215         newclient = j+1;
216       }
217       if (!putClientList(clients))
218         return 0; // failed to put the clientList to disk.
219     }
220     return newclient;
221   }
222   
223   /**
224    * safely writes clients array to the file referred to by sessionFile.
225    * 
226    * @param clients
227    * @return true if successful write. Throws Errors otherwise.
228    */
229   protected boolean putClientList(ClientHandle[] clients) {
230     if (lockFile()) {
231       File templist = backupSessionFile();
232       if (templist != null) {
233         try {
234           fileLock.rafile.setLength(0);
235           ObjectOutputStream os = new ObjectOutputStream(
236               new BufferedOutputStream(new FileOutputStream(this.sessionFile)));
237           os.writeObject(clients);
238           os.close();
239           // All done - remove the backup.
240           templist.delete();
241           templist = null;
242         } catch (Exception e) {
243           if (templist != null) {
244             System.err
245                 .println("Serious - problems writing to sessionFile. Backup in "
246                     + templist.getAbsolutePath());
247             e.printStackTrace(System.err);
248           }
249         }
250       } else {
251         throw new Error(
252             "Couldn't create backup of the clientList before writing to it!");
253       }
254     } else {
255       throw new Error("Could not lock the clientList: "
256           + ((sessionFile == null) ? "Unitialized ClientsFile"
257               : " failed to get lock on " + sessionFile.getAbsolutePath()));
258     }
259     // successful!
260     return true;
261   }
262 }