applied LGPLv3 and source code formatting.
[vamsas.git] / src / uk / ac / vamsas / client / simpleclient / ClientsFile.java
index e700ee4..f83324a 100644 (file)
-package uk.ac.vamsas.client.simpleclient;
-
-import uk.ac.vamsas.client.*;
-
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStreamReader;
-import java.io.ObjectInputStream;
-import java.io.ObjectOutput;
-import java.io.ObjectOutputStream;
-import java.io.OutputStream;
-import java.util.Vector;
-
-/**
- * Handler for the clientsFile within a vamsas session thread.
- * @author jim 
- */
-public class ClientsFile extends ListFile {
-  private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory.getLog(ClientsFile.class);
-  /**
-   * number of my client in list - passed back when a client 
-   * is added to list, and used (if valid) for quickly 
-   * looking up presence of client handle in the list.
-   */
-  private int syncnum = 1;
-
-  public ClientsFile(File filelist) throws IOException {
-    super(filelist);
-  }
-
-  /**
-   * internal method for getting clientList - ensures a lock has been made but
-   * does not release it.
-   * 
-   * @return list of clients
-   */
-  private ClientHandle[] retrieveClientHandles() {
-    if (lockFile()) {
-      try {
-        ClientHandle[] clients=null;
-        if (fileLock.length()>0) {
-          
-          ObjectInputStream is = new ObjectInputStream(fileLock.getBufferedInputStream(true));
-          Object o;
-          o=is.readObject();
-          if (o!=null) {
-            try {
-              clients = (ClientHandle[]) o;
-            }
-            catch (Exception e) {
-              System.err.println("Garbage in the clientHandle list "+this.sessionFile);
-            }
-          }
-        }
-        return clients;
-      } catch (FileNotFoundException e) {
-        // TODO Auto-generated catch block
-        e.printStackTrace(System.err);
-      } catch (Exception e) {
-        e.printStackTrace(System.err);
-      }
-    }
-    return null;
-  }
-  /**
-   * get the clientList from the file. May return null if lock failed!
-   * @return clientList
-   */
-  public ClientHandle[] retrieveClientList() {
-    if (lockFile()) {
-      ClientHandle[] clients = retrieveClientHandles();
-      unlockFile();
-      return clients;
-    }
-    return null;
-  }
-  /**
-   * get list from the locked ClientList.
-   * @param extantlock
-   * @return clientList or null if lock failed (or file was empty)
-   */
-  public ClientHandle[] retrieveClientList(Lock extantlock) {
-    if (lockFile(extantlock)) {
-      ClientHandle[] clients = retrieveClientHandles();
-      unlockFile();
-      return clients;
-    }
-    return null;
-  }
-  /**
-   * adds clientHandle me to the clientList under an existing lock extantLock.
-   * @param me
-   * @param extantLock
-   * @return client index in list or 0 if lock was invalid or addClient operation failed.
-   */
-  public int addClient(ClientHandle me, Lock extantLock) {
-    return addClient(me, true, extantLock);
-  }
-  
-  /**
-   * adds clientHandle me to the clientList under an existing lock.
-   * @param me - clientHandle
-   * @param disambig - if true then add will fail if an identical clientHandle already exists
-   * @param extantLock - existing lock
-   * @return client index in list or 0 if addClient (or the lock) failed.
-   */
-  
-  public int addClient(ClientHandle me, boolean disambig, Lock extantLock) {
-    if (lockFile(extantLock)) {
-      syncnum = addClient(me, disambig);
-      unlockFile();
-      return syncnum;
-    }
-    return 0;
-  }
-  
-  /**
-   * adds the ClientHandle to the list - if it is not unique, then the
-   * ClientHandle object is modified to make it unique in the list. returns the
-   * clientNumber for the client in the session.
-   * 
-   * @param me
-   * @return
-   */
-
-  public int addClient(ClientHandle me) {
-    syncnum = addClient(me, true);
-    unlockFile();
-    return syncnum;
-  }
-
-  /**
-   * removes 'me' from the session ClientList without complaint if 'me' isn't in the clientList already.
-   * @param me client handle to be removed
-   * @param clientlock existing lock passed from watcher.
-   */
-  public void removeClient(ClientHandle me, Lock clientlock) {
-    int mynum=-1;
-    if (lockFile(clientlock)) {
-      ClientHandle[] clients = retrieveClientHandles();
-      if (clients != null) {
-        if ((syncnum<=0 || syncnum>clients.length) || clients[syncnum-1]!=me) {
-          for (int i = 0, j = clients.length; i < j; i++) 
-            if (clients[i].equals(me)) {
-              mynum=i;
-              break;
-            }
-        } else {
-          mynum=syncnum-1;
-        }
-        if (mynum>-1) {
-          ClientHandle[] newlist = new ClientHandle[clients.length - 1];
-          for (int k=0,i = 0, j = clients.length; i < j; i++)
-            if (i!=mynum)
-              newlist[k++] = clients[i];
-          if (!putClientList(newlist))
-            throw new Error("Failed to write new clientList!"); // failed to put the clientList to disk.
-        }
-      }
-      unlockFile();
-    } else {
-      throw new Error("Couldn't get lock for "+((sessionFile==null) ? "Unitialised sessionFile in ClientsFile" : sessionFile.getAbsolutePath()));
-    }
-  }
-  /**
-   * Adds a ClientHandle to the ClientList file - optionally disambiguating 
-   * the ClientHandle (modifes the URN). 
-   * Note: Caller is left to release the lock on the ClientList.
-   * @param me
-   * @param disambiguate -
-   *          flag indicating if the URN for me should be disambiguated to
-   *          differentiate between sessions.
-   * @return index of clientHandle in new list, or -1-position of existing
-   *         clientHandle (if disambiguate is true)
-   */
-  protected int addClient(ClientHandle me, boolean disambiguate) {
-    int newclient = 0;
-    int tries=5;
-    while (tries-->0 && !lockFile())
-      try { Thread.sleep(1); } catch (Exception e){};
-    if (lockFile()) {
-      ClientHandle[] clients = retrieveClientHandles();
-      if (me.getClientUrn()==null) {
-        // TODO: move this into ClientUrn as a standard form method.
-        me.setClientUrn("vamsas://"+me.getClientName()+":"+me.getVersion()+"/");
-      }
-      if (clients == null) {
-        clients = new ClientHandle[1];
-        clients[0] = me;
-        newclient = 1;
-      } else {
-        int k = 0;
-        for (int i = 0, j = clients.length; i < j; i++) {
-          if (clients[i].equals(me)) {
-            if (disambiguate) {
-              while (clients[i].equals(me)) {
-                me.setClientUrn(me.getClientUrn() + k++); // TODO: make a better
-                                                          // disambiguation of
-                                                          // urn.
-              }
-            } else {
-              // will not write the ambiguous clientHandle to disk, just return
-              // its index.
-              return -1 - i;
-            }
-          }
-        }
-        int i, j;
-        ClientHandle[] newlist = new ClientHandle[clients.length + 1];
-        for (i = 0, j = clients.length; i < j; i++)
-          newlist[i] = clients[i];
-        newlist[j] = me;
-        clients = newlist;
-        newclient = j+1;
-      }
-      if (!putClientList(clients))
-        return 0; // failed to put the clientList to disk.
-    }
-    return newclient;
-  }
-  /**
-   * when set true - get FileNotFoundExceptions on WinXP when writing to locked stream after the backup has been made (via the backupFile method)
-   */
-  boolean backup=false;
-  /**
-   * safely writes clients array to the file referred to by sessionFile.
-   * 
-   * @param clients
-   * @return true if successful write. Throws Errors otherwise.
-   */
-  protected boolean putClientList(ClientHandle[] clients) {
-    if (lockFile()) {
-      File templist=null;
-      if (backup) {
-        templist = backupSessionFile();
-      }
-      if (!backup || (templist != null)) {
-        int retries=3;
-        while (retries-->0) {
-          try {
-            ObjectOutputStream os = 
-              new ObjectOutputStream(fileLock.getBufferedOutputStream(true));
-            log.debug("About to write "+clients.length+" clientHandles to output stream.");
-            os.writeObject(clients);
-            os.close();
-          // All done - remove the backup.
-          if (backup)
-            templist.delete();
-          templist = null;
-          retries=-1;
-          } catch (Exception e) {
-            System.err
-            .println("Serious - problems writing to sessionFile.");
-            if (retries>0 && templist != null) {
-              System.err.println("Recovering from Backup in "
-                      + templist.getAbsolutePath());
-              templist.renameTo(fileLock.target);
-            }
-            e.printStackTrace(System.err);
-          }
-        }
-        if (retries>-2) {
-          System.err
-          .println("Serious - problems writing to sessionFile. Giving Up.");
-          return false;
-        }
-      } else {
-        throw new Error(
-            "Couldn't create backup of the clientList before writing to it!");
-      }
-    } else {
-      throw new Error("Could not lock the clientList: "
-          + ((sessionFile == null) ? "Unitialized ClientsFile"
-              : " failed to get lock on " + sessionFile.getAbsolutePath()));
-    }
-    // successful!
-    return true;
-  }
-
-  public void clearList() {
-    if (lockFile()) {
-      try {
-        FileOutputStream fout = fileLock.getFileOutputStream(true);
-        fout.flush();
-        fout.close();
-      } catch (Exception e) {
-        throw new Error("Problems trying to clear clientlist!",e);
-        
-      }
-    }
-    
-  }
-}
+/*\r
+ * This file is part of the Vamsas Client version 0.1. \r
+ * Copyright 2009 by Jim Procter, Iain Milne, Pierre Marguerite, \r
+ *  Andrew Waterhouse and Dominik Lindner.\r
+ * \r
+ * Earlier versions have also been incorporated into Jalview version 2.4 \r
+ * since 2008, and TOPALi version 2 since 2007.\r
+ * \r
+ * The Vamsas Client is free software: you can redistribute it and/or modify\r
+ * it under the terms of the GNU Lesser General Public License as published by\r
+ * the Free Software Foundation, either version 3 of the License, or\r
+ * (at your option) any later version.\r
+ *  \r
+ * The Vamsas Client is distributed in the hope that it will be useful,\r
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
+ * GNU Lesser General Public License for more details.\r
+ * \r
+ * You should have received a copy of the GNU Lesser General Public License\r
+ * along with the Vamsas Client.  If not, see <http://www.gnu.org/licenses/>.\r
+ */\r
+package uk.ac.vamsas.client.simpleclient;\r
+\r
+import uk.ac.vamsas.client.*;\r
+\r
+import java.io.BufferedInputStream;\r
+import java.io.BufferedOutputStream;\r
+import java.io.File;\r
+import java.io.FileInputStream;\r
+import java.io.FileNotFoundException;\r
+import java.io.FileOutputStream;\r
+import java.io.IOException;\r
+import java.io.InputStreamReader;\r
+import java.io.ObjectInputStream;\r
+import java.io.ObjectOutput;\r
+import java.io.ObjectOutputStream;\r
+import java.io.OutputStream;\r
+import java.util.Vector;\r
+\r
+/**\r
+ * Handler for the clientsFile within a vamsas session thread.\r
+ * \r
+ * @author jim\r
+ */\r
+public class ClientsFile extends ListFile {\r
+  private static org.apache.commons.logging.Log log = org.apache.commons.logging.LogFactory\r
+      .getLog(ClientsFile.class);\r
+\r
+  /**\r
+   * number of my client in list - passed back when a client is added to list,\r
+   * and used (if valid) for quickly looking up presence of client handle in the\r
+   * list.\r
+   */\r
+  private int syncnum = 1;\r
+\r
+  public ClientsFile(File filelist) throws IOException {\r
+    super(filelist);\r
+  }\r
+\r
+  /**\r
+   * internal method for getting clientList - ensures a lock has been made but\r
+   * does not release it.\r
+   * \r
+   * @return list of clients\r
+   */\r
+  private ClientHandle[] retrieveClientHandles() {\r
+    if (lockFile()) {\r
+      try {\r
+        ClientHandle[] clients = null;\r
+        if (fileLock.length() > 0) {\r
+\r
+          ObjectInputStream is = new ObjectInputStream(fileLock\r
+              .getBufferedInputStream(true));\r
+          Object o;\r
+          o = is.readObject();\r
+          if (o != null) {\r
+            try {\r
+              clients = (ClientHandle[]) o;\r
+            } catch (Exception e) {\r
+              System.err.println("Garbage in the clientHandle list "\r
+                  + this.sessionFile);\r
+            }\r
+          }\r
+        }\r
+        return clients;\r
+      } catch (FileNotFoundException e) {\r
+        // TODO Auto-generated catch block\r
+        e.printStackTrace(System.err);\r
+      } catch (Exception e) {\r
+        e.printStackTrace(System.err);\r
+      }\r
+    }\r
+    return null;\r
+  }\r
+\r
+  /**\r
+   * get the clientList from the file. May return null if lock failed!\r
+   * \r
+   * @return clientList\r
+   */\r
+  public ClientHandle[] retrieveClientList() {\r
+    if (lockFile()) {\r
+      ClientHandle[] clients = retrieveClientHandles();\r
+      unlockFile();\r
+      return clients;\r
+    }\r
+    return null;\r
+  }\r
+\r
+  /**\r
+   * get list from the locked ClientList.\r
+   * \r
+   * @param extantlock\r
+   * @return clientList or null if lock failed (or file was empty)\r
+   */\r
+  public ClientHandle[] retrieveClientList(Lock extantlock) {\r
+    if (lockFile(extantlock)) {\r
+      ClientHandle[] clients = retrieveClientHandles();\r
+      unlockFile();\r
+      return clients;\r
+    }\r
+    return null;\r
+  }\r
+\r
+  /**\r
+   * adds clientHandle me to the clientList under an existing lock extantLock.\r
+   * \r
+   * @param me\r
+   * @param extantLock\r
+   * @return client index in list or 0 if lock was invalid or addClient\r
+   *         operation failed.\r
+   */\r
+  public int addClient(ClientHandle me, Lock extantLock) {\r
+    return addClient(me, true, extantLock);\r
+  }\r
+\r
+  /**\r
+   * adds clientHandle me to the clientList under an existing lock.\r
+   * \r
+   * @param me\r
+   *          - clientHandle\r
+   * @param disambig\r
+   *          - if true then add will fail if an identical clientHandle already\r
+   *          exists\r
+   * @param extantLock\r
+   *          - existing lock\r
+   * @return client index in list or 0 if addClient (or the lock) failed.\r
+   */\r
+\r
+  public int addClient(ClientHandle me, boolean disambig, Lock extantLock) {\r
+    if (lockFile(extantLock)) {\r
+      syncnum = addClient(me, disambig);\r
+      unlockFile();\r
+      return syncnum;\r
+    }\r
+    return 0;\r
+  }\r
+\r
+  /**\r
+   * adds the ClientHandle to the list - if it is not unique, then the\r
+   * ClientHandle object is modified to make it unique in the list. returns the\r
+   * clientNumber for the client in the session.\r
+   * \r
+   * @param me\r
+   * @return\r
+   */\r
+\r
+  public int addClient(ClientHandle me) {\r
+    syncnum = addClient(me, true);\r
+    unlockFile();\r
+    return syncnum;\r
+  }\r
+\r
+  /**\r
+   * removes 'me' from the session ClientList without complaint if 'me' isn't in\r
+   * the clientList already.\r
+   * \r
+   * @param me\r
+   *          client handle to be removed\r
+   * @param clientlock\r
+   *          existing lock passed from watcher.\r
+   */\r
+  public void removeClient(ClientHandle me, Lock clientlock) {\r
+    int mynum = -1;\r
+    if (lockFile(clientlock)) {\r
+      ClientHandle[] clients = retrieveClientHandles();\r
+      if (clients != null) {\r
+        if ((syncnum <= 0 || syncnum > clients.length)\r
+            || clients[syncnum - 1] != me) {\r
+          for (int i = 0, j = clients.length; i < j; i++)\r
+            if (clients[i].equals(me)) {\r
+              mynum = i;\r
+              break;\r
+            }\r
+        } else {\r
+          mynum = syncnum - 1;\r
+        }\r
+        if (mynum > -1) {\r
+          ClientHandle[] newlist = new ClientHandle[clients.length - 1];\r
+          for (int k = 0, i = 0, j = clients.length; i < j; i++)\r
+            if (i != mynum)\r
+              newlist[k++] = clients[i];\r
+          if (!putClientList(newlist))\r
+            throw new Error("Failed to write new clientList!"); // failed to put\r
+                                                                // the\r
+                                                                // clientList to\r
+                                                                // disk.\r
+        }\r
+      }\r
+      unlockFile();\r
+    } else {\r
+      throw new Error("Couldn't get lock for "\r
+          + ((sessionFile == null) ? "Unitialised sessionFile in ClientsFile"\r
+              : sessionFile.getAbsolutePath()));\r
+    }\r
+  }\r
+\r
+  /**\r
+   * Adds a ClientHandle to the ClientList file - optionally disambiguating the\r
+   * ClientHandle (modifes the URN). Note: Caller is left to release the lock on\r
+   * the ClientList.\r
+   * \r
+   * @param me\r
+   * @param disambiguate\r
+   *          - flag indicating if the URN for me should be disambiguated to\r
+   *          differentiate between sessions.\r
+   * @return index of clientHandle in new list, or -1-position of existing\r
+   *         clientHandle (if disambiguate is true)\r
+   */\r
+  protected int addClient(ClientHandle me, boolean disambiguate) {\r
+    int newclient = 0;\r
+    int tries = 5;\r
+    while (tries-- > 0 && !lockFile())\r
+      try {\r
+        Thread.sleep(1);\r
+      } catch (Exception e) {\r
+      }\r
+    ;\r
+    if (lockFile()) {\r
+      ClientHandle[] clients = retrieveClientHandles();\r
+      if (me.getClientUrn() == null) {\r
+        // TODO: move this into ClientUrn as a standard form method.\r
+        me.setClientUrn("vamsas://" + me.getClientName() + ":"\r
+            + me.getVersion() + "/");\r
+      }\r
+      if (clients == null) {\r
+        clients = new ClientHandle[1];\r
+        clients[0] = me;\r
+        newclient = 1;\r
+      } else {\r
+        int k = 0;\r
+        for (int i = 0, j = clients.length; i < j; i++) {\r
+          if (clients[i].equals(me)) {\r
+            if (disambiguate) {\r
+              while (clients[i].equals(me)) {\r
+                me.setClientUrn(me.getClientUrn() + k++); // TODO: make a better\r
+                // disambiguation of\r
+                // urn.\r
+              }\r
+            } else {\r
+              // will not write the ambiguous clientHandle to disk, just return\r
+              // its index.\r
+              return -1 - i;\r
+            }\r
+          }\r
+        }\r
+        int i, j;\r
+        ClientHandle[] newlist = new ClientHandle[clients.length + 1];\r
+        for (i = 0, j = clients.length; i < j; i++)\r
+          newlist[i] = clients[i];\r
+        newlist[j] = me;\r
+        clients = newlist;\r
+        newclient = j + 1;\r
+      }\r
+      if (!putClientList(clients))\r
+        return 0; // failed to put the clientList to disk.\r
+    }\r
+    return newclient;\r
+  }\r
+\r
+  /**\r
+   * when set true - get FileNotFoundExceptions on WinXP when writing to locked\r
+   * stream after the backup has been made (via the backupFile method)\r
+   */\r
+  boolean backup = false;\r
+\r
+  /**\r
+   * safely writes clients array to the file referred to by sessionFile.\r
+   * \r
+   * @param clients\r
+   * @return true if successful write. Throws Errors otherwise.\r
+   */\r
+  protected boolean putClientList(ClientHandle[] clients) {\r
+    if (lockFile()) {\r
+      File templist = null;\r
+      if (backup) {\r
+        templist = backupSessionFile();\r
+      }\r
+      if (!backup || (templist != null)) {\r
+        int retries = 3;\r
+        while (retries-- > 0) {\r
+          try {\r
+            ObjectOutputStream os = new ObjectOutputStream(fileLock\r
+                .getBufferedOutputStream(true));\r
+            log.debug("About to write " + clients.length\r
+                + " clientHandles to output stream.");\r
+            os.writeObject(clients);\r
+            os.close();\r
+            // All done - remove the backup.\r
+            if (backup)\r
+              templist.delete();\r
+            templist = null;\r
+            retries = -1;\r
+          } catch (Exception e) {\r
+            System.err.println("Serious - problems writing to sessionFile.");\r
+            if (retries > 0 && templist != null) {\r
+              System.err.println("Recovering from Backup in "\r
+                  + templist.getAbsolutePath());\r
+              templist.renameTo(fileLock.target);\r
+            }\r
+            e.printStackTrace(System.err);\r
+          }\r
+        }\r
+        if (retries > -2) {\r
+          System.err\r
+              .println("Serious - problems writing to sessionFile. Giving Up.");\r
+          return false;\r
+        }\r
+      } else {\r
+        throw new Error(\r
+            "Couldn't create backup of the clientList before writing to it!");\r
+      }\r
+    } else {\r
+      throw new Error("Could not lock the clientList: "\r
+          + ((sessionFile == null) ? "Unitialized ClientsFile"\r
+              : " failed to get lock on " + sessionFile.getAbsolutePath()));\r
+    }\r
+    // successful!\r
+    return true;\r
+  }\r
+\r
+  public void clearList() {\r
+    if (lockFile()) {\r
+      try {\r
+        FileOutputStream fout = fileLock.getFileOutputStream(true);\r
+        fout.flush();\r
+        fout.close();\r
+      } catch (Exception e) {\r
+        throw new Error("Problems trying to clear clientlist!", e);\r
+\r
+      }\r
+    }\r
+\r
+  }\r
+}\r